Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(web-app): folder bridge, workspace/project menu and skill destination on the home composer

Akarshan Biswas88008a3aed46
diff --git a/web-app/src/constants/__tests__/chat.test.ts b/web-app/src/constants/__tests__/chat.test.ts
new file mode 100644
index 000000000..45a23f128
--- /dev/null
+++ b/web-app/src/constants/__tests__/chat.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest'
+import { isTemporaryChatSearch } from '../chat'
+
+describe('isTemporaryChatSearch', () => {
+ it.each([
+ '?temporary-chat=true',
+ 'temporary-chat=true',
+ '?a=1&temporary-chat=true',
+ '?temporary%2Dchat=true',
+ '?temporary-chat=%74rue',
+ '?temporary-chat=true&temporary-chat=false',
+ '?temporary-chat=false&temporary-chat=true',
+ '?temporary-chat=true&temporary-chat=true',
+ '?temporary-chat=false&temporary-chat=truex&temporary-chat=true',
+ '?temporary-chat=%5Btrue%2Cfalse%5D',
+ '?temporary-chat=%5Bfalse%2Ctrue%5D',
+ '?temporary-chat=%5B%22true%22%2Cfalse%5D',
+ '?temporary-chat=%5Btrue%2Ctrue%5D',
+ ])('accepts %s', (search) => {
+ expect(isTemporaryChatSearch(search)).toBe(true)
+ })
+
+ it.each([
+ '',
+ '?',
+ '?temporary-chat',
+ '?temporary-chat=',
+ '?temporary-chat=truex',
+ '?temporary-chat=True',
+ '?x-temporary-chat=true',
+ '?temporary-chatx=true',
+ '?temporary-chat=false',
+ '?temporary-chat=false&temporary-chat=false',
+ '?temporary-chat=truex&temporary-chat=xtrue',
+ '?temporary-chat=%5Bfalse%2Cfalse%5D',
+ '?temporary-chat=%5B%22truex%22%2Cfalse%5D',
+ '?temporary-chat=%5B%22True%22%5D',
+ '?temporary-chat=%5B%5Btrue%5D%5D',
+ '?temporary-chat=%5B%7B%22a%22%3Atrue%7D%5D',
+ '?temporary-chat=%5Btrue',
+ '?temporary-chat=%5B%5D',
+ '?x-temporary-chat=true&temporary-chat=false',
+ '?other=temporary-chat%3Dtrue',
+ ])('rejects %s', (search) => {
+ expect(isTemporaryChatSearch(search)).toBe(false)
+ })
+
+ // Intentional, documented over-match: a single array literal `[true]` is
+ // not "exactly true", but the router round-trips it as an array and the
+ // detector fails privacy-closed. It can only hide/restrict access, never
+ // grant any. The same applies to a quoted "true" inside an array.
+ it.each([
+ '?temporary-chat=[true]',
+ '?temporary-chat=%5Btrue%5D',
+ '?temporary-chat=%5B%22true%22%5D',
+ ])('intentionally treats single-element array %s as temporary (privacy-closed)', (search) => {
+ expect(isTemporaryChatSearch(search)).toBe(true)
+ })
+
+ it('treats missing search as not temporary', () => {
+ expect(isTemporaryChatSearch(undefined)).toBe(false)
+ expect(isTemporaryChatSearch(null)).toBe(false)
+ })
+})
diff --git a/web-app/src/constants/chat.ts b/web-app/src/constants/chat.ts
index 4e8f60912..83a422847 100644
--- a/web-app/src/constants/chat.ts
+++ b/web-app/src/constants/chat.ts
@@ -5,6 +5,40 @@
export const TEMPORARY_CHAT_ID = 'temporary-chat'
export const TEMPORARY_CHAT_QUERY_ID = 'temporary-chat'
+/**
+ * Single source of truth for the temporary-chat query flag. Parses with
+ * URLSearchParams (decoded keys/values). It fails PRIVACY-CLOSED: the chat is
+ * temporary when ANY `temporary-chat` value is exactly `true`, regardless of
+ * duplicate order (`?temporary-chat=false&temporary-chat=true` -> true).
+ * Substrings like `truex` or `x-temporary-chat=true` never match.
+ *
+ * The actual router does not hand consumers a raw string. Its default
+ * parse/stringify folds duplicate keys into a JSON array and re-encodes it, so
+ * `location.searchStr` is `?temporary-chat=%5Btrue%2Cfalse%5D`, which decodes
+ * to the text `[true,false]`. A value that parses as a JSON array containing
+ * boolean `true` or string `"true"` is therefore also temporary; arrays with
+ * only other elements (e.g. `[false,false]`) are not.
+ */
+export function isTemporaryChatSearch(search: string | null | undefined): boolean {
+ return new URLSearchParams(search ?? '')
+ .getAll(TEMPORARY_CHAT_QUERY_ID)
+ .some(isTemporaryChatValue)
+}
+
+function isTemporaryChatValue(value: string): boolean {
+ if (value === 'true') return true
+ if (!value.startsWith('[')) return false
+ try {
+ const parsed: unknown = JSON.parse(value)
+ return (
+ Array.isArray(parsed) &&
+ parsed.some((item) => item === true || item === 'true')
+ )
+ } catch {
+ return false
+ }
+}
+
/**
* Session storage keys for initial messages
*/
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index b16d21932..3b4a8c521 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -109,6 +109,10 @@ import {
} from '@/lib/path-references'
import { FilePickerPopover } from '@/components/FilePickerPopover'
import { ContributedMenuItems } from '@/containers/extensions/ContributedMenuItems'
+import type {
+ FolderDraftOutcome,
+ FolderDraftSubmission,
+} from '@/lib/startCoworkFromDraft'
type ChatInputProps = {
className?: string
@@ -167,6 +171,19 @@ type ChatInputProps = {
*/
tokenSource?: TokenUsageSource
highlightedPrefix?: string | null
+ /**
+ * Extra entries for the + menu that the surface owns (workspace and project
+ * actions). Rendered as menu items; ChatInput adds the separator.
+ */
+ menuWorkspace?: ReactNode
+ /**
+ * Home-style surfaces only. Called instead of creating a chat thread when
+ * the draft carries a folder, so the surface can start the conversation on
+ * the runner that can use it. `'chat'` falls through to an ordinary chat.
+ */
+ onFolderDraft?: (
+ submission: FolderDraftSubmission
+ ) => Promise<FolderDraftOutcome> | FolderDraftOutcome
}
// Video containers llama-server can decode via ffmpeg/ffprobe into frames.
@@ -204,6 +221,8 @@ const ChatInput = memo(function ChatInput({
surfaceControls,
tokenSource,
highlightedPrefix,
+ menuWorkspace,
+ onFolderDraft,
}: ChatInputProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null)
const highlightRef = useRef<HTMLDivElement>(null)
@@ -617,6 +636,42 @@ const ChatInput = memo(function ChatInput({
{}
)
+ // Media go to the model as file parts; documents travel as attachments.
+ const collectMedia = () => {
+ const imageFiles = attachments
+ .filter((att) => att.type === 'image' && att.dataUrl)
+ .map((att) => ({
+ type: 'file' as const,
+ mediaType: att.mimeType ?? 'image/jpeg',
+ url: att.dataUrl!,
+ }))
+ const audioFiles = attachments
+ .filter((att) => att.type === 'audio' && att.dataUrl)
+ .map((att) => ({
+ type: 'file' as const,
+ mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
+ url: att.dataUrl!,
+ }))
+ const videoFiles = attachments
+ .filter((att) => att.type === 'video' && att.dataUrl)
+ .map((att) => ({
+ type: 'file' as const,
+ mediaType: att.mimeType ?? 'video/mp4',
+ url: att.dataUrl!,
+ }))
+ const files = [...imageFiles, ...audioFiles, ...videoFiles]
+ const documents = attachments.filter(
+ (att) => att.type === 'document' && att.path
+ )
+
+ return {
+ files: files.length > 0 ? files : undefined,
+ documents: documents.length > 0 ? documents : undefined,
+ }
+ }
+
+ const folderStarting = useRef(false)
+
const handleSendMessage = async (prompt: string) => {
if (!selectedModel) {
setMessage('Please select a model to start chatting.')
@@ -657,36 +712,12 @@ const ChatInput = memo(function ChatInput({
return
}
- const imageFiles = attachments
- .filter((att) => att.type === 'image' && att.dataUrl)
- .map((att) => ({
- type: 'file' as const,
- mediaType: att.mimeType ?? 'image/jpeg',
- url: att.dataUrl!,
- }))
- const audioFiles = attachments
- .filter((att) => att.type === 'audio' && att.dataUrl)
- .map((att) => ({
- type: 'file' as const,
- mediaType: att.audioFormat === 'mp3' ? 'audio/mpeg' : 'audio/wav',
- url: att.dataUrl!,
- }))
- const videoFiles = attachments
- .filter((att) => att.type === 'video' && att.dataUrl)
- .map((att) => ({
- type: 'file' as const,
- mediaType: att.mimeType ?? 'video/mp4',
- url: att.dataUrl!,
- }))
- const files = [...imageFiles, ...audioFiles, ...videoFiles]
- const documents = attachments.filter(
- (att) => att.type === 'document' && att.path
- )
+ const { files, documents } = collectMedia()
onSubmit(
effectivePrompt,
- files.length > 0 ? files : undefined,
- documents.length > 0 ? documents : undefined,
+ files,
+ documents,
prompt
)
setPrompt('')
@@ -725,6 +756,31 @@ const ChatInput = memo(function ChatInput({
params: { threadId: TEMPORARY_CHAT_ID },
})
} else {
+ // A draft with a folder starts on the Cowork runner (the surface decides
+ // and navigates); anything else is an ordinary chat thread.
+ if (onFolderDraft) {
+ if (folderStarting.current) return
+ folderStarting.current = true
+ try {
+ const { files, documents } = collectMedia()
+ const outcome = await onFolderDraft({
+ text: effectivePrompt,
+ draft: prompt,
+ files,
+ documents,
+ })
+ if (outcome === 'refused') return
+ if (outcome === 'started') {
+ setPrompt('')
+ // The run owns its copies now (handoff), so the draft's go.
+ clearAttachmentsForThread(attachmentsKey)
+ return
+ }
+ } finally {
+ folderStarting.current = false
+ }
+ }
+
// Get project metadata and assistant if projectId is provided
let projectMetadata:
| { id: string; name: string; updated_at: number }
@@ -2404,6 +2460,12 @@ const ChatInput = memo(function ChatInput({
</DropdownMenuItem>
</>
)}
+ {menuWorkspace && (
+ <>
+ <DropdownMenuSeparator />
+ {menuWorkspace}
+ </>
+ )}
{/* Only chat threads: a scoped surface (Cowork) has no thread id. */}
{!scopeKey && currentThreadId && (
<ContributedMenuItems
diff --git a/web-app/src/containers/CoworkComposerMenu.tsx b/web-app/src/containers/CoworkComposerMenu.tsx
new file mode 100644
index 000000000..ae7764a01
--- /dev/null
+++ b/web-app/src/containers/CoworkComposerMenu.tsx
@@ -0,0 +1,93 @@
+import { Check, Folder, FolderPlus } from 'lucide-react'
+import {
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from '@/components/ui/dropdown-menu'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import type { ThreadFolder } from '@/services/projects/types'
+
+type Props = {
+ projects?: ThreadFolder[]
+ projectId?: string
+ /** Absent when the surface cannot attach a folder (browser build). */
+ onAttachFolder?: () => void
+ /** Absent on a surface whose project is fixed (a project page). */
+ onSelectProject?: (project: ThreadFolder) => void
+ onAddProject?: () => void
+}
+
+/**
+ * Workspace and project entries of the composer's + menu. They are owned by the
+ * surface that creates the conversation; ChatInput owns attachments and the
+ * shared tool controls.
+ */
+export function CoworkComposerMenu({
+ projects = [],
+ projectId,
+ onAttachFolder,
+ onSelectProject,
+ onAddProject,
+}: Props) {
+ const { t } = useTranslation()
+ const canPickProject = !!onSelectProject || !!onAddProject
+ return (
+ <>
+ {onAttachFolder && (
+ <DropdownMenuItem onSelect={onAttachFolder}>
+ <FolderPlus className="size-4 text-muted-foreground" />
+ {t('common:homeMode.addFolderAction')}
+ </DropdownMenuItem>
+ )}
+ {canPickProject && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Folder className="size-4 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ {t('common:homeMode.addToProject')}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ className="flex max-h-(--radix-dropdown-menu-content-available-height) w-64 flex-col"
+ sideOffset={4}
+ >
+ <DropdownMenuGroup className="min-h-0 max-h-64 overflow-y-auto">
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ disabled={!onSelectProject}
+ onSelect={() => onSelectProject?.(project)}
+ >
+ <Folder className="size-4 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{project.name}</span>
+ <span className="flex size-4 shrink-0 items-center justify-center">
+ {projectId === project.id && (
+ <Check className="size-4 text-primary" />
+ )}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ {!projects.length && (
+ <DropdownMenuItem disabled>
+ {t('common:homeMode.noProjects')}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuGroup>
+ {onAddProject && (
+ <>
+ <DropdownMenuSeparator className="shrink-0" />
+ <DropdownMenuItem className="shrink-0" onSelect={onAddProject}>
+ <FolderPlus className="size-4 text-muted-foreground" />
+ {t('common:homeMode.newProject')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ </>
+ )
+}
diff --git a/web-app/src/containers/CoworkPage.tsx b/web-app/src/containers/CoworkPage.tsx
index 3af6ea772..b737c3150 100644
--- a/web-app/src/containers/CoworkPage.tsx
+++ b/web-app/src/containers/CoworkPage.tsx
@@ -71,6 +71,13 @@ import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'
import { CoworkPlanToggle } from '@/containers/CoworkPlanToggle'
import { CoworkEmptyState } from '@/containers/CoworkEmptyState'
import { usePrompt } from '@/hooks/usePrompt'
+import { useChatAttachments } from '@/hooks/useChatAttachments'
+import {
+ claimCoworkHandoff,
+ clearCoworkHandoff,
+ peekCoworkHandoff,
+ releaseCoworkHandoff,
+} from '@/lib/coworkHandoff'
import { awaitsModel } from '@/lib/agentActivity'
import { artifactsFromParts, artifactsFromTurns } from '@/lib/coworkArtifacts'
import { sessionAttachments } from '@/lib/coworkFiles'
@@ -452,7 +459,9 @@ export function CoworkPage() {
const runRequest = async (
text: string | null,
attachments?: CoworkAttachments,
- sid = ensureCurrentSession()
+ sid = ensureCurrentSession(),
+ /** Called once the run is claimed, i.e. the request was not refused. */
+ onAccepted?: () => void
) => {
const store = useCoworkSessions.getState()
const current = store.sessions.find((s) => s.id === sid)
@@ -505,6 +514,7 @@ export function CoworkPage() {
useCoworkRun
.getState()
.beginRun(sid, handle.runId, text ?? '', attachments?.media)
+ onAccepted?.()
// The window-close handshake (see coworkSync) must stop this run and wait
// for its final commit: until the `finally` below commits, the transcript
// and wire history exist only in this closure. Registered synchronously with
@@ -1139,6 +1149,66 @@ export function CoworkPage() {
const runRequestRef = useRef(runRequest)
runRequestRef.current = runRequest
+ // First prompt handed over from the home composer (the folder bridge). Read
+ // without removing and cleared only once the run is accepted: runRequest
+ // refuses (no usable model, no tool support) before it claims the session,
+ // and a refused first prompt must come back to the composer instead of
+ // vanishing. `claim` makes the effect safe to run twice (StrictMode), so the
+ // prompt is never sent twice.
+ const sessionId = session?.id
+ const sessionUnavailable = !!session?.unavailable
+ useEffect(() => {
+ if (!sessionId || sessionUnavailable || isCoworkClosing()) return
+ const handoff = peekCoworkHandoff(sessionId)
+ if (!handoff || !claimCoworkHandoff(sessionId)) return
+ let accepted = false
+ void runRequestRef
+ .current(
+ handoff.text,
+ {
+ media: handoff.files,
+ files: handoff.documents
+ ?.filter((d): d is Attachment & { path: string } => !!d.path)
+ .map((d) => ({
+ name: d.name,
+ path: d.path,
+ fileType: d.fileType,
+ size: d.size,
+ })),
+ },
+ sessionId,
+ () => {
+ accepted = true
+ clearCoworkHandoff(sessionId)
+ }
+ )
+ .then(() => {
+ if (accepted) return
+ // Refused: hand the draft back and let a later attempt start fresh.
+ usePrompt.getState().setPrompt(handoff.draft ?? handoff.text)
+ useChatAttachments.getState().setAttachments(sessionId, [
+ ...(handoff.documents ?? []),
+ ...(handoff.files ?? []).map(
+ (file, index): Attachment => ({
+ name: `Attachment ${index + 1}`,
+ type: file.mediaType.startsWith('audio/')
+ ? 'audio'
+ : file.mediaType.startsWith('video/')
+ ? 'video'
+ : 'image',
+ mimeType: file.mediaType,
+ dataUrl: file.url,
+ ...(file.mediaType === 'audio/mpeg'
+ ? { audioFormat: 'mp3' as const }
+ : {}),
+ })
+ ),
+ ])
+ clearCoworkHandoff(sessionId)
+ releaseCoworkHandoff(sessionId)
+ })
+ }, [sessionId, sessionUnavailable])
+
/**
* `/compact`: summarize everything but the recent tail into one system
* message, reusing the transport's auto-compact machinery (context-manager).
diff --git a/web-app/src/containers/DraftProjectChip.tsx b/web-app/src/containers/DraftProjectChip.tsx
new file mode 100644
index 000000000..2a67cac4c
--- /dev/null
+++ b/web-app/src/containers/DraftProjectChip.tsx
@@ -0,0 +1,31 @@
+import { Folder, X } from 'lucide-react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import type { ThreadFolder } from '@/services/projects/types'
+
+/** The Jan project the next conversation will be filed under. */
+export function DraftProjectChip({
+ project,
+ onRemove,
+}: {
+ project: ThreadFolder
+ onRemove: () => void
+}) {
+ const { t } = useTranslation()
+ return (
+ <div
+ className="flex items-center gap-2 pt-2 text-sm text-muted-foreground"
+ data-testid="home-chat-project"
+ >
+ <Folder className="size-4 shrink-0" aria-hidden="true" />
+ <span className="min-w-0 truncate">{project.name}</span>
+ <button
+ type="button"
+ className="rounded-sm p-1 hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={t('common:conversationScope.removeProject')}
+ onClick={onRemove}
+ >
+ <X className="size-4" aria-hidden="true" />
+ </button>
+ </div>
+ )
+}
diff --git a/web-app/src/containers/DraftWorkspacePill.tsx b/web-app/src/containers/DraftWorkspacePill.tsx
new file mode 100644
index 000000000..1fd5a1567
--- /dev/null
+++ b/web-app/src/containers/DraftWorkspacePill.tsx
@@ -0,0 +1,28 @@
+import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'
+
+/**
+ * The folder pill for a conversation that does not exist yet. It edits the
+ * pending draft only; the folder takes effect when the first message creates the
+ * conversation. Nothing shows until a folder is chosen: the + menu is where one
+ * is added.
+ */
+export function DraftWorkspacePill({
+ folder,
+ onPickFolder,
+ onDetach,
+}: {
+ folder: string | null
+ onPickFolder: () => void
+ onDetach: () => void
+}) {
+ if (!folder) return null
+ return (
+ <div className="pt-2" data-testid="draft-workspace-pill">
+ <CoworkWorkspacePill
+ folder={folder}
+ onAttach={onPickFolder}
+ onDetach={onDetach}
+ />
+ </div>
+ )
+}
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index 961b5683c..738fd5855 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -806,6 +806,69 @@ describe('ChatInput', () => {
})
})
+ describe('menuWorkspace', () => {
+ it('adds the surface-owned workspace entries to the + menu', () => {
+ renderInput({ menuWorkspace: <button>add-folder</button> })
+ expect(screen.getByText('add-folder')).toBeInTheDocument()
+ })
+
+ it('adds nothing when the surface supplies none', () => {
+ renderInput()
+ expect(screen.queryByText('add-folder')).toBeNull()
+ })
+ })
+
+ describe('onFolderDraft (home composer with a folder)', () => {
+ const submit = () =>
+ fireEvent.keyDown(getTextarea(), { key: 'Enter' })
+
+ it('hands the draft over and creates no chat thread when the surface starts it', async () => {
+ promptState = 'work on this'
+ const onFolderDraft = vi.fn().mockResolvedValue('started')
+ renderInput({ onSubmit: undefined, onFolderDraft })
+ submit()
+ await waitFor(() => expect(onFolderDraft).toHaveBeenCalledTimes(1))
+ expect(onFolderDraft).toHaveBeenCalledWith({
+ text: 'work on this',
+ draft: 'work on this',
+ files: undefined,
+ documents: undefined,
+ })
+ expect(createThreadMock).not.toHaveBeenCalled()
+ expect(clearAttachmentsMock).toHaveBeenCalled()
+ })
+
+ it('keeps the attachments and creates no thread when the surface refuses', async () => {
+ promptState = 'work on this'
+ const onFolderDraft = vi.fn().mockResolvedValue('refused')
+ renderInput({ onSubmit: undefined, onFolderDraft })
+ submit()
+ await waitFor(() => expect(onFolderDraft).toHaveBeenCalledTimes(1))
+ expect(createThreadMock).not.toHaveBeenCalled()
+ expect(clearAttachmentsMock).not.toHaveBeenCalled()
+ })
+
+ it('falls through to an ordinary chat thread when there is no folder', async () => {
+ promptState = 'just chat'
+ createThreadMock.mockResolvedValue({ id: 'new-thread' })
+ const onFolderDraft = vi.fn().mockResolvedValue('chat')
+ renderInput({ onSubmit: undefined, onFolderDraft })
+ submit()
+ await waitFor(() => expect(createThreadMock).toHaveBeenCalledTimes(1))
+ expect(onFolderDraft).toHaveBeenCalledTimes(1)
+ })
+
+ it('is not consulted by a surface that submits through onSubmit', async () => {
+ promptState = 'in a thread'
+ const onSubmit = vi.fn()
+ const onFolderDraft = vi.fn().mockResolvedValue('started')
+ renderInput({ onSubmit, onFolderDraft })
+ submit()
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())
+ expect(onFolderDraft).not.toHaveBeenCalled()
+ })
+ })
+
describe('image size limit', () => {
const MB = 1024 * 1024
const imageFile = (name: string, bytes: number, type = 'image/png') => {
diff --git a/web-app/src/containers/__tests__/CoworkComposerMenu.test.tsx b/web-app/src/containers/__tests__/CoworkComposerMenu.test.tsx
new file mode 100644
index 000000000..6066993eb
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkComposerMenu.test.tsx
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import '@testing-library/jest-dom/vitest'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}))
+// Flatten the menu primitives: Radix portals/sub-menus need pointer geometry.
+vi.mock('@/components/ui/dropdown-menu', () => {
+ const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>
+ return {
+ DropdownMenuGroup: Pass,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: Pass,
+ DropdownMenuSubContent: Pass,
+ DropdownMenuSubTrigger: Pass,
+ DropdownMenuItem: ({
+ children,
+ onSelect,
+ disabled,
+ }: {
+ children?: React.ReactNode
+ onSelect?: () => void
+ disabled?: boolean
+ }) => (
+ <button disabled={disabled} onClick={() => onSelect?.()}>
+ {children}
+ </button>
+ ),
+ }
+})
+
+import { CoworkComposerMenu } from '../CoworkComposerMenu'
+
+const projects = [
+ { id: 'a', name: 'Alpha', updated_at: 1 },
+ { id: 'b', name: 'Beta', updated_at: 2 },
+]
+
+describe('CoworkComposerMenu', () => {
+ it('attaches a folder and picks or creates a project', async () => {
+ const onAttachFolder = vi.fn()
+ const onSelectProject = vi.fn()
+ const onAddProject = vi.fn()
+ render(
+ <CoworkComposerMenu
+ projects={projects}
+ projectId="a"
+ onAttachFolder={onAttachFolder}
+ onSelectProject={onSelectProject}
+ onAddProject={onAddProject}
+ />
+ )
+ await userEvent.click(screen.getByText('common:homeMode.addFolderAction'))
+ await userEvent.click(screen.getByText('Beta'))
+ await userEvent.click(screen.getByText('common:homeMode.newProject'))
+ expect(onAttachFolder).toHaveBeenCalledTimes(1)
+ expect(onSelectProject).toHaveBeenCalledWith(projects[1])
+ expect(onAddProject).toHaveBeenCalledTimes(1)
+ })
+
+ it('offers no folder action where the host cannot attach one', () => {
+ render(<CoworkComposerMenu projects={projects} onSelectProject={vi.fn()} />)
+ expect(screen.queryByText('common:homeMode.addFolderAction')).toBeNull()
+ expect(screen.getByText('common:homeMode.addToProject')).toBeInTheDocument()
+ })
+
+ it('offers no project submenu on a surface whose project is fixed', () => {
+ render(<CoworkComposerMenu onAttachFolder={vi.fn()} />)
+ expect(screen.getByText('common:homeMode.addFolderAction')).toBeInTheDocument()
+ expect(screen.queryByText('common:homeMode.addToProject')).toBeNull()
+ })
+
+ it('says so when there are no projects yet', () => {
+ render(<CoworkComposerMenu onSelectProject={vi.fn()} />)
+ expect(screen.getByText('common:homeMode.noProjects')).toBeDisabled()
+ })
+})
diff --git a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx b/web-app/src/containers/dialogs/SkillsManagerDialog.tsx
index e854f75fd..5c11fa8c6 100644
--- a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx
+++ b/web-app/src/containers/dialogs/SkillsManagerDialog.tsx
@@ -12,7 +12,9 @@ import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useParams } from '@tanstack/react-router'
import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { useThreads } from '@/hooks/useThreads'
import { useSkills, type HubSkill } from '@/hooks/useSkills'
export default function SkillsManagerDialog({
@@ -23,11 +25,28 @@ export default function SkillsManagerDialog({
onOpenChange: (open: boolean) => void
}) {
const { t } = useTranslation()
- const sessions = useCoworkSessions((s) => s.sessions)
- const currentId = useCoworkSessions((s) => s.currentId)
- const folder = sessions.find((s) => s.id === currentId)?.folder ?? null
+ // The folder comes from the conversation on screen, not from whichever Cowork
+ // session was selected last: the store keeps `currentId` after the user leaves.
+ const { sessionId, threadId } = useParams({ strict: false }) as {
+ sessionId?: string
+ threadId?: string
+ }
+ const sessionFolder = useCoworkSessions(
+ (s) => s.sessions.find((x) => x.id === sessionId)?.folder ?? null
+ )
+ const threadFolder = useThreads((s) => {
+ const folder = threadId ? s.threads[threadId]?.metadata?.folder : null
+ return typeof folder === 'string' ? folder : null
+ })
+ const folder = sessionId ? sessionFolder : threadFolder
- const { skills, remove, write, read, hubList, hubImport } = useSkills(folder)
+ // A new skill goes to the chosen destination; existing ones stay where they
+ // live. With no folder there is only the global store.
+ const [destination, setDestination] = useState<'folder' | 'global'>('folder')
+ const { skills, remove, write, read, hubList, hubImport } = useSkills(
+ folder,
+ destination
+ )
const localNames = new Set(skills.map((s) => s.name))
// `selected` is the skill being edited; '' with isNew means a fresh draft.
@@ -286,6 +305,31 @@ export default function SkillsManagerDialog({
placeholder={t('common:skillNamePlaceholder')}
disabled={!isNew}
/>
+ {isNew && folder && (
+ <div
+ role="group"
+ aria-label={t('common:skillDestination')}
+ className="flex items-center gap-2 text-xs text-muted-foreground"
+ >
+ <span>{t('common:skillDestination')}</span>
+ {(['folder', 'global'] as const).map((choice) => (
+ <Button
+ key={choice}
+ type="button"
+ size="xs"
+ variant={destination === choice ? 'secondary' : 'ghost'}
+ aria-pressed={destination === choice}
+ onClick={() => setDestination(choice)}
+ >
+ {t(
+ choice === 'folder'
+ ? 'common:skillDestinationFolder'
+ : 'common:skillDestinationGlobal'
+ )}
+ </Button>
+ ))}
+ </div>
+ )}
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
diff --git a/web-app/src/hooks/__tests__/useFolderDraft.test.tsx b/web-app/src/hooks/__tests__/useFolderDraft.test.tsx
new file mode 100644
index 000000000..3042ffec1
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useFolderDraft.test.tsx
@@ -0,0 +1,118 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+
+const h = vi.hoisted(() => ({
+ searchStr: '',
+ picked: '/home/u/app' as unknown,
+ tauri: true,
+ model: { id: 'm', capabilities: ['tools'] } as unknown,
+ navigate: vi.fn(),
+ start: vi.fn(),
+ info: vi.fn(),
+}))
+
+vi.mock('@tanstack/react-router', () => ({
+ useLocation: ({ select }: { select: (l: { searchStr: string }) => string }) =>
+ select({ searchStr: h.searchStr }),
+ useRouter: () => ({ navigate: h.navigate }),
+}))
+vi.mock('sonner', () => ({ toast: { info: h.info, error: vi.fn() } }))
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}))
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: (selector: (s: unknown) => unknown) =>
+ selector({ selectedModel: h.model }),
+}))
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({ dialog: () => ({ open: async () => h.picked }) }),
+}))
+vi.mock('@/lib/coworkSync', () => ({ supportsCowork: () => h.tauri }))
+vi.mock('@/lib/startCoworkFromDraft', () => ({
+ startCoworkFromDraft: (...args: unknown[]) => h.start(...args),
+}))
+
+import { useFolderDraft } from '../useFolderDraft'
+
+const submission = { text: 'hi', draft: 'hi' }
+
+describe('useFolderDraft', () => {
+ beforeEach(() => {
+ h.searchStr = ''
+ h.picked = '/home/u/app'
+ h.tauri = true
+ h.model = { id: 'm', capabilities: ['tools'] }
+ h.start.mockReset().mockReturnValue('started')
+ h.info.mockReset()
+ })
+
+ it('is an ordinary chat while no folder is attached', () => {
+ const { result } = renderHook(() => useFolderDraft())
+ expect(result.current.onFolderDraft(submission)).toBe('chat')
+ expect(h.start).not.toHaveBeenCalled()
+ })
+
+ it('starts a cowork conversation with the attached folder, then forgets it', async () => {
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ expect(result.current.folder).toBe('/home/u/app')
+ let outcome = ''
+ act(() => {
+ outcome = result.current.onFolderDraft(submission)
+ })
+ expect(outcome).toBe('started')
+ expect(h.start).toHaveBeenCalledWith(
+ expect.objectContaining({ folder: '/home/u/app', submission })
+ )
+ expect(result.current.folder).toBeNull()
+ })
+
+ it('keeps the folder when the run was refused', async () => {
+ h.start.mockReturnValue('refused')
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ act(() => {
+ result.current.onFolderDraft(submission)
+ })
+ expect(result.current.folder).toBe('/home/u/app')
+ })
+
+ it('does not offer a folder to a model without tools', async () => {
+ h.model = { id: 'plain', capabilities: [] }
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ expect(result.current.folder).toBeNull()
+ expect(h.info).toHaveBeenCalledWith('common:conversationScope.folderUnsupported')
+ })
+
+ it('asks for a model before offering a folder', async () => {
+ h.model = undefined
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ expect(result.current.folder).toBeNull()
+ expect(h.info).toHaveBeenCalledWith('common:conversationScope.folderSelectModel')
+ })
+
+ it('ignores a cancelled folder dialog', async () => {
+ h.picked = null
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ expect(result.current.folder).toBeNull()
+ })
+
+ it('keeps no workspace in a temporary chat', async () => {
+ h.searchStr = '?temporary-chat=true'
+ const { result } = renderHook(() => useFolderDraft())
+ await act(async () => result.current.attach())
+ expect(result.current.folder).toBeNull()
+ expect(result.current.onFolderDraft(submission)).toBe('chat')
+ expect(h.info).toHaveBeenCalledWith('common:conversationScope.temporary')
+ })
+
+ it('is unavailable outside the desktop host', () => {
+ h.tauri = false
+ const { result } = renderHook(() => useFolderDraft())
+ expect(result.current.available).toBe(false)
+ expect(result.current.onFolderDraft(submission)).toBe('chat')
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useSkills.destination.test.ts b/web-app/src/hooks/__tests__/useSkills.destination.test.ts
new file mode 100644
index 000000000..cd235c8ee
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useSkills.destination.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook, waitFor } from '@testing-library/react'
+
+const h = vi.hoisted(() => ({
+ writes: [] as Array<{ scope: { kind: string; folder?: string }; name: string }>,
+}))
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: async (command: string) =>
+ command === 'agent_skill_enabled_get' ? [] : null,
+}))
+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
+vi.mock('@/hooks/useServiceHub', () => ({ getServiceHub: () => ({}) }))
+vi.mock('@/lib/skillStore', () => ({
+ storeScope: { kind: 'store' },
+ projectScope: (folder: string) => ({ kind: 'project', folder }),
+ listSkills: async () => [],
+ writeSkill: async (
+ scope: { kind: string; folder?: string },
+ name: string
+ ) => {
+ h.writes.push({ scope, name })
+ },
+}))
+
+import { useSkills } from '../useSkills'
+
+describe('useSkills destination for a new skill', () => {
+ beforeEach(() => {
+ h.writes = []
+ })
+
+ it('writes to the attached folder by default', async () => {
+ const { result } = renderHook(() => useSkills('/project'))
+ await act(async () => result.current.write('a', 'body'))
+ expect(h.writes).toEqual([
+ { scope: { kind: 'project', folder: '/project' }, name: 'a' },
+ ])
+ })
+
+ it('writes to the global store when that destination is chosen', async () => {
+ const { result } = renderHook(() => useSkills('/project', 'global'))
+ await act(async () => result.current.write('a', 'body'))
+ expect(h.writes).toEqual([{ scope: { kind: 'store' }, name: 'a' }])
+ })
+
+ it('writes to the global store when there is no folder', async () => {
+ const { result } = renderHook(() => useSkills(null, 'folder'))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+ await act(async () => result.current.write('a', 'body'))
+ expect(h.writes).toEqual([{ scope: { kind: 'store' }, name: 'a' }])
+ })
+})
diff --git a/web-app/src/hooks/useFolderDraft.ts b/web-app/src/hooks/useFolderDraft.ts
new file mode 100644
index 000000000..3704c305b
--- /dev/null
+++ b/web-app/src/hooks/useFolderDraft.ts
@@ -0,0 +1,76 @@
+import { useCallback, useMemo, useState } from 'react'
+import { useLocation, useRouter } from '@tanstack/react-router'
+import { toast } from 'sonner'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useModelProvider } from '@/hooks/useModelProvider'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import { isTemporaryChatSearch } from '@/constants/chat'
+import { supportsCowork } from '@/lib/coworkSync'
+import {
+ startCoworkFromDraft,
+ type FolderDraftOutcome,
+ type FolderDraftSubmission,
+} from '@/lib/startCoworkFromDraft'
+import type { ThreadFolder } from '@/services/projects/types'
+
+/**
+ * The folder half of a home-style draft (home and project pages). The folder is
+ * route-local intent: it never carries over to another conversation, and a
+ * temporary chat ignores it (it keeps no workspace).
+ */
+export function useFolderDraft(project?: ThreadFolder | null) {
+ const { t } = useTranslation()
+ const router = useRouter()
+ const serviceHub = useServiceHub()
+ const selectedModel = useModelProvider((s) => s.selectedModel)
+ const [folder, setFolder] = useState<string | null>(null)
+ const searchStr = useLocation({ select: (location) => location.searchStr })
+ const isTemporaryChat = isTemporaryChatSearch(searchStr)
+ // Folders need the desktop host; the browser build never offers one.
+ const available = supportsCowork()
+ const activeFolder = available && !isTemporaryChat ? folder : null
+
+ const attach = useCallback(async () => {
+ if (isTemporaryChat) {
+ toast.info(t('common:conversationScope.temporary'))
+ return
+ }
+ if (!selectedModel) {
+ toast.info(t('common:conversationScope.folderSelectModel'))
+ return
+ }
+ if (!selectedModel.capabilities?.includes('tools')) {
+ toast.info(t('common:conversationScope.folderUnsupported'))
+ return
+ }
+ const picked = await serviceHub.dialog().open({ directory: true })
+ if (typeof picked !== 'string') return
+ setFolder(picked)
+ }, [isTemporaryChat, selectedModel, serviceHub, t])
+
+ const onFolderDraft = useCallback(
+ (submission: FolderDraftSubmission): FolderDraftOutcome => {
+ if (!activeFolder) return 'chat'
+ const outcome = startCoworkFromDraft({
+ folder: activeFolder,
+ project,
+ submission,
+ navigate: (options) => router.navigate(options as never),
+ })
+ if (outcome === 'started') setFolder(null)
+ return outcome
+ },
+ [activeFolder, project, router]
+ )
+
+ return useMemo(
+ () => ({
+ available,
+ folder: activeFolder,
+ attach: () => void attach(),
+ detach: () => setFolder(null),
+ onFolderDraft,
+ }),
+ [available, activeFolder, attach, onFolderDraft]
+ )
+}
diff --git a/web-app/src/hooks/useHomeScope.ts b/web-app/src/hooks/useHomeScope.ts
new file mode 100644
index 000000000..5557bbeea
--- /dev/null
+++ b/web-app/src/hooks/useHomeScope.ts
@@ -0,0 +1,9 @@
+import { useState } from 'react'
+import type { ThreadFolder } from '@/services/projects/types'
+
+/** Home draft intent, not authorization. Route-local lifetime prevents a
+ * completed conversation's project/assistant leaking into the next draft. */
+export function useHomeScope() {
+ const [project, setProject] = useState<ThreadFolder | null>(null)
+ return { project, setProject }
+}
diff --git a/web-app/src/hooks/useSkills.ts b/web-app/src/hooks/useSkills.ts
index 84754a827..d879219f9 100644
--- a/web-app/src/hooks/useSkills.ts
+++ b/web-app/src/hooks/useSkills.ts
@@ -61,7 +61,11 @@ const useSkillsVersion = create<{ v: number; bump: () => void }>((set) => ({
* `[skills].enabled` whitelist stays a project concern: with no folder it has
* nowhere to live, so everything reads as enabled and `setEnabled` is a no-op.
*/
-export function useSkills(folder: string | null) {
+export function useSkills(
+ folder: string | null,
+ /** Where a brand-new skill is written when a folder is attached. */
+ destination: 'folder' | 'global' = 'folder'
+) {
const [skills, setSkills] = useState<ScopedSkill[]>([])
// Enabled-skill whitelist from `[skills].enabled`; empty = all skills enabled.
const [enabled, setEnabledState] = useState<string[]>([])
@@ -75,10 +79,14 @@ export function useSkills(folder: string | null) {
// without depending on (and being recreated by) the `skills` state.
const originRef = useRef<Map<string, SkillOrigin>>(new Map())
- // Where a NEW skill is written: the folder's store when attached, else global.
+ // Where a NEW skill is written: the chosen destination (the folder's store
+ // by default when one is attached), else global.
const newScope = useMemo(
- () => (folder ? skillStore.projectScope(folder) : skillStore.storeScope),
- [folder]
+ () =>
+ folder && destination === 'folder'
+ ? skillStore.projectScope(folder)
+ : skillStore.storeScope,
+ [folder, destination]
)
const scopeOf = useCallback(
(name: string) => {
diff --git a/web-app/src/lib/__tests__/startCoworkFromDraft.test.ts b/web-app/src/lib/__tests__/startCoworkFromDraft.test.ts
new file mode 100644
index 000000000..00bf89ccb
--- /dev/null
+++ b/web-app/src/lib/__tests__/startCoworkFromDraft.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }))
+vi.mock('sonner', () => ({ toast: { error: toastError } }))
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ i18n: { t: (key: string) => key },
+}))
+
+import { startCoworkFromDraft } from '../startCoworkFromDraft'
+import { peekCoworkHandoff, clearCoworkHandoff } from '../coworkHandoff'
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { useModelProvider } from '@/hooks/useModelProvider'
+
+const tools = { id: 'm', capabilities: ['tools'] }
+const noTools = { id: 'plain', capabilities: [] }
+
+const setModel = (
+ model: { id: string; capabilities: string[] },
+ source?: string
+) =>
+ useModelProvider.setState({
+ providers: [
+ { provider: 'p', active: true, models: [model], settings: [], source },
+ ] as never,
+ selectedProvider: 'p',
+ selectedModel: model as never,
+ })
+
+const submission = { text: 'hello', draft: 'hello' }
+
+describe('startCoworkFromDraft', () => {
+ const navigate = vi.fn()
+ beforeEach(() => {
+ navigate.mockReset()
+ toastError.mockReset()
+ sessionStorage.clear()
+ useCoworkSessions.setState({ sessions: [], currentId: null })
+ setModel(tools)
+ })
+
+ it('creates exactly one cowork session with the folder and one handoff', () => {
+ const outcome = startCoworkFromDraft({
+ folder: '/home/u/app',
+ submission,
+ navigate,
+ })
+ const { sessions } = useCoworkSessions.getState()
+ expect(outcome).toBe('started')
+ expect(sessions).toHaveLength(1)
+ expect(sessions[0].folder).toBe('/home/u/app')
+ expect(sessions[0].model).toEqual({ provider: 'p', id: 'm' })
+ expect(peekCoworkHandoff(sessions[0].id)?.text).toBe('hello')
+ expect(navigate).toHaveBeenCalledTimes(1)
+ expect(navigate).toHaveBeenCalledWith({
+ to: '/cowork/$sessionId',
+ params: { sessionId: sessions[0].id },
+ })
+ clearCoworkHandoff(sessions[0].id)
+ })
+
+ it('files the conversation under the draft project', () => {
+ const project = { id: 'pr', name: 'Proj', updated_at: 1 }
+ startCoworkFromDraft({ folder: '/home/u/app', project, submission, navigate })
+ expect(useCoworkSessions.getState().sessions[0].project).toMatchObject({
+ id: 'pr',
+ name: 'Proj',
+ })
+ })
+
+ it('does not inherit a plan mode left on an untouched current session', () => {
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().setPlanMode(id, true)
+ startCoworkFromDraft({ folder: '/home/u/app', submission, navigate })
+ expect(useCoworkSessions.getState().sessions).toHaveLength(1)
+ expect(useCoworkSessions.getState().sessions[0].planMode).toBe(false)
+ })
+
+ it('refuses before creating anything when the model cannot use tools', () => {
+ setModel(noTools)
+ const outcome = startCoworkFromDraft({
+ folder: '/home/u/app',
+ submission,
+ navigate,
+ })
+ expect(outcome).toBe('refused')
+ expect(useCoworkSessions.getState().sessions).toHaveLength(0)
+ expect(navigate).not.toHaveBeenCalled()
+ expect(toastError).toHaveBeenCalledWith('common:modelNoTools')
+ })
+
+ it('refuses a provider added by an extension', () => {
+ setModel(tools, 'some-extension')
+ expect(
+ startCoworkFromDraft({ folder: '/home/u/app', submission, navigate })
+ ).toBe('refused')
+ expect(useCoworkSessions.getState().sessions).toHaveLength(0)
+ })
+
+ it('refuses when no model is selected', () => {
+ useModelProvider.setState({ selectedModel: undefined } as never)
+ expect(
+ startCoworkFromDraft({ folder: '/home/u/app', submission, navigate })
+ ).toBe('refused')
+ expect(navigate).not.toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/lib/coworkSync.ts b/web-app/src/lib/coworkSync.ts
index f51627f0e..5099aae8e 100644
--- a/web-app/src/lib/coworkSync.ts
+++ b/web-app/src/lib/coworkSync.ts
@@ -13,6 +13,7 @@ import {
import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'
import { useThreads } from '@/hooks/useThreads'
import { getServiceHub } from '@/hooks/useServiceHub'
+import { discardStaleCoworkHandoffs } from '@/lib/coworkHandoff'
import {
isPlatformAndroid,
isPlatformIOS,
@@ -142,7 +143,8 @@ export async function flushCowork(): Promise<void> {
await persistence?.flush()
}
-const supportsCowork = () =>
+/** Cowork needs the desktop host (native folder dialog, sandboxed tools). */
+export const supportsCowork = () =>
isPlatformTauri() && !isPlatformIOS() && !isPlatformAndroid()
/** Resolves with the work's outcome, or with `'timeout'` after `ms`. */
@@ -272,6 +274,16 @@ async function doStart() {
// sidebar see them. Do this once; later writes upsert through onThreadWritten.
for (const t of loaded.threads) upsertThread(t)
+ // A first prompt handed over from the home composer for a session that no
+ // longer exists (reload before its first commit) must not linger.
+ try {
+ discardStaleCoworkHandoffs(
+ new Set(useCoworkSessions.getState().sessions.map((x) => x.id))
+ )
+ } catch {
+ /* sessionStorage unavailable */
+ }
+
// 4. Write-through from here on.
let prev = useCoworkSessions.getState()
const legacyIds = loaded.legacyIds
diff --git a/web-app/src/lib/startCoworkFromDraft.ts b/web-app/src/lib/startCoworkFromDraft.ts
new file mode 100644
index 000000000..9a4bd0296
--- /dev/null
+++ b/web-app/src/lib/startCoworkFromDraft.ts
@@ -0,0 +1,97 @@
+import { toast } from 'sonner'
+import { i18n } from '@/i18n/react-i18next-compat'
+import { useCoworkSessions } from '@/hooks/useCoworkSessions'
+import { useModelProvider } from '@/hooks/useModelProvider'
+import { coworkAllowsProvider } from '@/lib/coworkModelControls'
+import { writeCoworkHandoff } from '@/lib/coworkHandoff'
+import { route } from '@/constants/routes'
+import type { Attachment } from '@/types/attachment'
+import type { ThreadFolder } from '@/services/projects/types'
+
+/** What the composer hands over when the home draft carries a folder. */
+export type FolderDraftSubmission = {
+ /** The prompt with @path references expanded. */
+ text: string
+ /** What the user typed, so a refused run can hand it back unchanged. */
+ draft: string
+ files?: Array<{ type: 'file'; mediaType: string; url: string }>
+ documents?: Attachment[]
+}
+
+/**
+ * - `started`: a Cowork conversation was created and opened; the first prompt
+ * travels to it through the handoff.
+ * - `refused`: nothing was created; the draft stays in the composer.
+ * - `chat`: not a folder conversation, send it as an ordinary chat.
+ */
+export type FolderDraftOutcome = 'started' | 'refused' | 'chat'
+
+type Navigate = (options: {
+ to: string
+ params: { sessionId: string }
+}) => unknown
+
+/**
+ * The interim folder bridge. The Chat executor cannot use a folder yet, so a
+ * home draft that carries one starts a `mode: 'cowork'` conversation, run by the
+ * Cowork runner on its first prompt. This is the only place a new Cowork
+ * conversation is created, and it is explicit: no folder, no Cowork.
+ *
+ * It refuses up front what the runner would refuse after navigating (no model,
+ * no tool support, a provider Cowork cannot use), so the user keeps the draft
+ * and the folder instead of landing on an empty page.
+ */
+export function startCoworkFromDraft(args: {
+ folder: string
+ project?: ThreadFolder | null
+ submission: FolderDraftSubmission
+ navigate: Navigate
+}): FolderDraftOutcome {
+ const { folder, project, submission, navigate } = args
+ const t = i18n.t.bind(i18n)
+ const { providers, selectedProvider, selectedModel } =
+ useModelProvider.getState()
+ if (!selectedModel?.id) {
+ toast.error(t('common:selectModel'))
+ return 'refused'
+ }
+ const provider = providers.find(
+ (p) => p.provider === selectedProvider && p.active
+ )
+ if (!coworkAllowsProvider(provider)) {
+ toast.error(t('common:coworkExtensionProvider'))
+ return 'refused'
+ }
+ if (!selectedModel.capabilities?.includes('tools')) {
+ toast.error(t('common:modelNoTools', { model: selectedModel.id }))
+ return 'refused'
+ }
+
+ const store = useCoworkSessions.getState()
+ const sessionId = store.createSession()
+ // createSession reuses an untouched current session, so set every field the
+ // draft decides rather than assume a blank one.
+ store.setFolder(sessionId, folder)
+ store.setModel(sessionId, { provider: selectedProvider, id: selectedModel.id })
+ store.setPlanMode(sessionId, false)
+ store.setProject(
+ sessionId,
+ project
+ ? {
+ id: project.id,
+ name: project.name,
+ updated_at: project.updated_at,
+ assistantId: project.assistantId,
+ }
+ : undefined
+ )
+ try {
+ writeCoworkHandoff(sessionId, submission)
+ } catch (error) {
+ console.warn('[cowork] could not hand the first prompt over:', error)
+ toast.error(t('common:homeMode.startFailed'))
+ return 'refused'
+ }
+ void navigate({ to: route.coworkSession, params: { sessionId } })
+ return 'started'
+}
diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.json
index 41e5a977b..fc9046945 100644
--- a/web-app/src/locales/de-DE/common.json
+++ b/web-app/src/locales/de-DE/common.json
@@ -475,5 +475,21 @@
"xhigh": "Sehr hoch",
"unlimited": "Unbegrenzt"
}
- }
+ },
+ "homeMode": {
+ "addToProject": "Zu einem Projekt hinzufügen",
+ "newProject": "Neues Projekt",
+ "noProjects": "Noch keine Projekte",
+ "addFolderAction": "Ordner hinzufügen",
+ "startFailed": "Die Unterhaltung konnte nicht gestartet werden. Deine Nachricht steht weiterhin im Eingabefeld."
+ },
+ "conversationScope": {
+ "folderSelectModel": "Wähle ein Modell mit Werkzeugunterstützung, bevor du Ordnerzugriff hinzufügst.",
+ "folderUnsupported": "Dieses Modell kann keine Werkzeuge nutzen, daher lässt sich kein Ordner hinzufügen. Normales Chatten funktioniert weiterhin.",
+ "removeProject": "Projektauswahl entfernen",
+ "temporary": "Ein temporärer Chat behält keinen Ordnerzugriff."
+ },
+ "skillDestination": "Neue Skills speichern in",
+ "skillDestinationFolder": "Diesem Ordner",
+ "skillDestinationGlobal": "Global (jede Unterhaltung)"
}
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index edb8385d7..b3029e473 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -853,5 +853,21 @@
"xhigh": "Very high",
"unlimited": "Unlimited"
}
- }
+ },
+ "homeMode": {
+ "addToProject": "Add to a project",
+ "newProject": "New project",
+ "noProjects": "No projects yet",
+ "addFolderAction": "Add folder",
+ "startFailed": "Could not start the conversation. Your message is still in the box."
+ },
+ "conversationScope": {
+ "folderSelectModel": "Select a tool-capable model before adding folder access.",
+ "folderUnsupported": "This model can't use tools, so a folder can't be added. Regular chat still works.",
+ "removeProject": "Remove project selection",
+ "temporary": "A temporary chat keeps no folder access."
+ },
+ "skillDestination": "Save new skills to",
+ "skillDestinationFolder": "This folder",
+ "skillDestinationGlobal": "Global (every conversation)"
}
diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.json
index 96cfaac3f..3dbeafa45 100644
--- a/web-app/src/locales/fr/common.json
+++ b/web-app/src/locales/fr/common.json
@@ -478,5 +478,21 @@
"xhigh": "Très élevé",
"unlimited": "Illimité"
}
- }
+ },
+ "homeMode": {
+ "addToProject": "Ajouter à un projet",
+ "newProject": "Nouveau projet",
+ "noProjects": "Aucun projet pour le moment",
+ "addFolderAction": "Ajouter un dossier",
+ "startFailed": "Impossible de démarrer la conversation. Votre message est toujours dans la zone de saisie."
+ },
+ "conversationScope": {
+ "folderSelectModel": "Sélectionnez un modèle compatible avec les outils avant d’ajouter l’accès à un dossier.",
+ "folderUnsupported": "Ce modèle ne peut pas utiliser d’outils : impossible d’ajouter un dossier. La discussion normale fonctionne toujours.",
+ "removeProject": "Retirer la sélection du projet",
+ "temporary": "Une discussion temporaire ne conserve aucun accès aux dossiers."
+ },
+ "skillDestination": "Enregistrer les nouvelles compétences dans",
+ "skillDestinationFolder": "Ce dossier",
+ "skillDestinationGlobal": "Global (toutes les conversations)"
}
diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.json
index 97ca04387..49e6bf160 100644
--- a/web-app/src/locales/ja/common.json
+++ b/web-app/src/locales/ja/common.json
@@ -592,5 +592,21 @@
"xhigh": "最高",
"unlimited": "無制限"
}
- }
+ },
+ "homeMode": {
+ "addToProject": "プロジェクトに追加",
+ "newProject": "新しいプロジェクト",
+ "noProjects": "プロジェクトはまだありません",
+ "addFolderAction": "フォルダーを追加",
+ "startFailed": "会話を開始できませんでした。メッセージは入力欄に残っています。"
+ },
+ "conversationScope": {
+ "folderSelectModel": "フォルダーへのアクセスを追加する前に、ツール対応モデルを選択してください。",
+ "folderUnsupported": "このモデルはツールを使用できないため、フォルダーを追加できません。通常のチャットは引き続き使えます。",
+ "removeProject": "プロジェクトの選択を解除",
+ "temporary": "一時チャットではフォルダーへのアクセスは保持されません。"
+ },
+ "skillDestination": "新しいスキルの保存先",
+ "skillDestinationFolder": "このフォルダー",
+ "skillDestinationGlobal": "グローバル(すべての会話)"
}
diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.json
index 45c335f77..f64600006 100644
--- a/web-app/src/locales/zh-CN/common.json
+++ b/web-app/src/locales/zh-CN/common.json
@@ -654,5 +654,21 @@
"xhigh": "极高",
"unlimited": "不限"
}
- }
+ },
+ "homeMode": {
+ "addToProject": "添加到项目",
+ "newProject": "新建项目",
+ "noProjects": "暂无项目",
+ "addFolderAction": "添加文件夹",
+ "startFailed": "无法开始对话。您的消息仍保留在输入框中。"
+ },
+ "conversationScope": {
+ "folderSelectModel": "添加文件夹访问权限前,请先选择支持工具的模型。",
+ "folderUnsupported": "此模型无法使用工具,因此无法添加文件夹。普通聊天仍可使用。",
+ "removeProject": "取消选择项目",
+ "temporary": "临时聊天不会保留文件夹访问权限。"
+ },
+ "skillDestination": "新技能保存到",
+ "skillDestinationFolder": "此文件夹",
+ "skillDestinationGlobal": "全局(所有对话)"
}
diff --git a/web-app/src/routes/__tests__/coworkSkills.test.tsx b/web-app/src/routes/__tests__/coworkSkills.test.tsx
index 1685a4416..3f1779bc5 100644
--- a/web-app/src/routes/__tests__/coworkSkills.test.tsx
+++ b/web-app/src/routes/__tests__/coworkSkills.test.tsx
@@ -1,7 +1,7 @@
import '@testing-library/jest-dom/vitest'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { beforeEach, expect, it, vi } from 'vitest'
-import type { ReactNode } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { StrictMode, type ReactNode } from 'react'
import type { UIMessage } from 'ai'
import type * as CoworkRunner from '@/lib/coworkRunner'
@@ -258,6 +258,11 @@ import { useCoworkRun } from '@/hooks/useCoworkRun'
import { useMessageQueue } from '@/stores/message-queue-store'
import { useModelProvider } from '@/hooks/useModelProvider'
import { answerAsk } from '@/lib/coworkRunner'
+import {
+ claimCoworkHandoff,
+ peekCoworkHandoff,
+ writeCoworkHandoff,
+} from '@/lib/coworkHandoff'
import {
sessionFromThread,
sessionToThreadRecord,
@@ -653,3 +658,63 @@ it.each([
).toBe(planMode)
}
)
+
+describe('first-prompt handoff from the home composer', () => {
+ const handoffSession = (text: string) => {
+ const id = useCoworkSessions.getState().createSession()
+ useCoworkSessions.getState().setFolder(id, '/project')
+ writeCoworkHandoff(id, { text, draft: text })
+ return id
+ }
+
+ it('runs the handed-over prompt exactly once under StrictMode', async () => {
+ const id = handoffSession('First from home')
+ render(
+ <StrictMode>
+ <CoworkPage />
+ </StrictMode>
+ )
+ await waitFor(() => expect(backend.received).toHaveLength(1))
+ await act(async () => {})
+ expect(backend.received).toHaveLength(1)
+ expect(backend.received[0].at(-1)?.parts).toContainEqual({
+ type: 'text',
+ text: 'First from home',
+ })
+ expect(peekCoworkHandoff(id)).toBeNull()
+ })
+
+ it('does not run it again when the page remounts after the run was accepted', async () => {
+ handoffSession('Only once')
+ const view = render(<CoworkPage />)
+ await waitFor(() => expect(backend.received).toHaveLength(1))
+ view.unmount()
+ render(<CoworkPage />)
+ await act(async () => {})
+ expect(backend.received).toHaveLength(1)
+ })
+
+ it('hands a refused first prompt back to the composer and keeps it retryable', async () => {
+ useModelProvider.setState({
+ providers: [
+ {
+ provider: 'test',
+ active: true,
+ api_key: 'test',
+ models: [{ id: 'test-model', capabilities: [] }],
+ settings: [],
+ },
+ ],
+ selectedModel: { id: 'test-model', capabilities: [] },
+ } as never)
+ const id = handoffSession('Refused draft')
+ render(<CoworkPage />)
+ await waitFor(() =>
+ expect(usePrompt.getState().prompt).toBe('Refused draft')
+ )
+ expect(backend.received).toHaveLength(0)
+ expect(peekCoworkHandoff(id)).toBeNull()
+ // A later handoff for the same session id is claimable again.
+ expect(claimCoworkHandoff(id)).toBe(true)
+ })
+})
diff --git a/web-app/src/routes/__tests__/index.test.tsx b/web-app/src/routes/__tests__/index.test.tsx
index c69a1abc6..94f1130cb 100644
--- a/web-app/src/routes/__tests__/index.test.tsx
+++ b/web-app/src/routes/__tests__/index.test.tsx
@@ -9,6 +9,7 @@ const h = vi.hoisted(() => ({
search: { threadModel: undefined as any },
setCurrentThreadId: vi.fn(),
useTools: vi.fn(),
+ folder: null as string | null,
providerHasRemoteApiKeys: vi.fn(() => false),
predefinedProviders: [
{ provider: 'openai' },
@@ -34,6 +35,33 @@ vi.mock('@/hooks/useThreads', () => ({
useThreads: () => ({ setCurrentThreadId: h.setCurrentThreadId }),
}))
+vi.mock('@/hooks/useFolderDraft', () => ({
+ useFolderDraft: () => ({
+ available: true,
+ folder: h.folder,
+ attach: vi.fn(),
+ detach: vi.fn(),
+ onFolderDraft: vi.fn(),
+ }),
+}))
+
+vi.mock('@/hooks/useThreadManagement', () => ({
+ useThreadManagement: () => ({ addFolder: vi.fn(), folders: [] }),
+}))
+
+vi.mock('@/containers/dialogs/AddProjectDialog', () => ({
+ default: () => null,
+}))
+
+vi.mock('@/containers/CoworkComposerMenu', () => ({
+ CoworkComposerMenu: () => null,
+}))
+
+vi.mock('@/containers/DraftWorkspacePill', () => ({
+ DraftWorkspacePill: ({ folder }: any) =>
+ folder ? <div data-testid="draft-pill">{folder}</div> : null,
+}))
+
vi.mock('@/hooks/useTools', () => ({
useTools: h.useTools,
}))
@@ -82,6 +110,7 @@ describe('Index route', () => {
vi.clearAllMocks()
h.providers = []
h.search = { threadModel: undefined }
+ h.folder = null
h.providerHasRemoteApiKeys.mockReturnValue(false)
})
@@ -160,4 +189,15 @@ describe('Index route', () => {
expect(h.setCurrentThreadId).toHaveBeenCalledWith(undefined)
expect(h.useTools).toHaveBeenCalled()
})
+
+ it('shows the folder pill only once a folder is attached', () => {
+ h.providers = [{ provider: 'openai', models: [] }]
+ h.providerHasRemoteApiKeys.mockReturnValue(true)
+ const { unmount } = renderComponent()
+ expect(screen.queryByTestId('draft-pill')).toBeNull()
+ unmount()
+ h.folder = '/home/u/project'
+ renderComponent()
+ expect(screen.getByTestId('draft-pill')).toHaveTextContent('/home/u/project')
+ })
})
diff --git a/web-app/src/routes/index.tsx b/web-app/src/routes/index.tsx
index 0020fcef2..a0b2e02b8 100644
--- a/web-app/src/routes/index.tsx
+++ b/web-app/src/routes/index.tsx
@@ -19,8 +19,15 @@ type ThreadModel = {
type SearchParams = {
threadModel?: ThreadModel
}
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { useThreads } from '@/hooks/useThreads'
+import { CoworkComposerMenu } from '@/containers/CoworkComposerMenu'
+import { DraftWorkspacePill } from '@/containers/DraftWorkspacePill'
+import { DraftProjectChip } from '@/containers/DraftProjectChip'
+import AddProjectDialog from '@/containers/dialogs/AddProjectDialog'
+import { useThreadManagement } from '@/hooks/useThreadManagement'
+import { useHomeScope } from '@/hooks/useHomeScope'
+import { useFolderDraft } from '@/hooks/useFolderDraft'
export const Route = createFileRoute(route.home as any)({
component: Index,
@@ -41,6 +48,15 @@ function Index() {
const { setCurrentThreadId } = useThreads()
useTools()
+ // One home flow: every new conversation is an ordinary chat unless the user
+ // explicitly attaches a folder, which starts it on the Cowork runner (see
+ // useFolderDraft). No mode selector, no hidden classifier. The project is
+ // route-local intent so it never leaks into the next draft.
+ const { project, setProject } = useHomeScope()
+ const [projectDialogOpen, setProjectDialogOpen] = useState(false)
+ const { addFolder, folders: projects } = useThreadManagement()
+ const workspace = useFolderDraft(project)
+
const hasValidProviders = hasUsableProvider(providers)
useEffect(() => {
@@ -53,6 +69,16 @@ function Index() {
return (
<div className="flex h-full flex-col justify-center">
+ <AddProjectDialog
+ open={projectDialogOpen}
+ onOpenChange={setProjectDialogOpen}
+ editingKey={null}
+ onSave={async (name, assistantId) => {
+ const created = await addFolder(name, assistantId)
+ setProject(created)
+ setProjectDialogOpen(false)
+ }}
+ />
<HeaderPage />
<div
className={cn(
@@ -78,8 +104,31 @@ function Index() {
showSpeedToken={false}
model={threadModel}
initialMessage={true}
+ projectId={project?.id}
+ projectAssistantId={project?.assistantId}
+ menuWorkspace={
+ <CoworkComposerMenu
+ projects={projects}
+ projectId={project?.id}
+ onAttachFolder={workspace.available ? workspace.attach : undefined}
+ onSelectProject={setProject}
+ onAddProject={() => setProjectDialogOpen(true)}
+ />
+ }
+ onFolderDraft={workspace.onFolderDraft}
/>
</div>
+ <DraftWorkspacePill
+ folder={workspace.folder}
+ onPickFolder={workspace.attach}
+ onDetach={workspace.detach}
+ />
+ {project && (
+ <DraftProjectChip
+ project={project}
+ onRemove={() => setProject(null)}
+ />
+ )}
</div>
</div>
</div>
diff --git a/web-app/src/routes/project/$projectId.tsx b/web-app/src/routes/project/$projectId.tsx
index 0df5fac41..ecf93df05 100644
--- a/web-app/src/routes/project/$projectId.tsx
+++ b/web-app/src/routes/project/$projectId.tsx
@@ -25,6 +25,9 @@ import AddProjectDialog from '@/containers/dialogs/AddProjectDialog'
import { DeleteProjectDialog } from '@/containers/dialogs/DeleteProjectDialog'
import { DeleteAllThreadsInProjectDialog } from '@/containers/dialogs/DeleteAllThreadsInProjectDialog'
import { SidebarMenu } from '@/components/ui/sidebar'
+import { CoworkComposerMenu } from '@/containers/CoworkComposerMenu'
+import { DraftWorkspacePill } from '@/containers/DraftWorkspacePill'
+import { useFolderDraft } from '@/hooks/useFolderDraft'
export const Route = createFileRoute('/project/$projectId')({
component: ProjectPageContent,
@@ -44,6 +47,9 @@ function ProjectPageContent() {
// Find the project
const project = getFolderById(projectId)
+ // A folder attached here starts the project's next conversation on the Cowork
+ // runner, filed under this project.
+ const workspace = useFolderDraft(project)
// Find the assigned assistant
const projectAssistant = useMemo(() => {
@@ -126,6 +132,17 @@ function ProjectPageContent() {
initialMessage={true}
projectId={projectId}
projectAssistantId={project.assistantId}
+ menuWorkspace={
+ <CoworkComposerMenu
+ onAttachFolder={workspace.available ? workspace.attach : undefined}
+ />
+ }
+ onFolderDraft={workspace.onFolderDraft}
+ />
+ <DraftWorkspacePill
+ folder={workspace.folder}
+ onPickFolder={workspace.attach}
+ onDetach={workspace.detach}
/>
</div>