Skip to content

Build and run agents you can see, understand and trust.

feat(web-ui): session working directory with git status (#2257)

DavdGaoa3738ed322c0
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 0dca2e988..3054bda2c 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -1,6 +1,6 @@
export * from './types';
export { agentApi } from './agent';
-export { sessionApi } from './session';
+export { sessionApi, takeFreshlyCreated } from './session';
export { credentialApi } from './credential';
export { chatApi } from './chat';
export { workspaceApi } from './workspace';
diff --git a/examples/web_ui/frontend/src/api/session.ts b/examples/web_ui/frontend/src/api/session.ts
index 4fdc16728..eaee9222c 100644
--- a/examples/web_ui/frontend/src/api/session.ts
+++ b/examples/web_ui/frontend/src/api/session.ts
@@ -16,13 +16,54 @@ export interface MessagesResponse {
has_more: boolean;
}
+/**
+ * Sessions this tab created and has not opened yet.
+ *
+ * A session created here cannot have any history, so asking the server
+ * for it is a guaranteed-empty round trip — and one that paints a
+ * loading state over a conversation the user is about to start.
+ *
+ * Entries are consumed on first read: once the session has been opened,
+ * anything written to it afterwards (a scheduled run, a team member)
+ * must be fetched normally.
+ */
+const freshlyCreated = new Set<string>();
+
+/**
+ * Whether `sessionId` was created by this tab and not yet opened.
+ * Consumes the flag, so a second call for the same id returns false.
+ *
+ * @param sessionId - The session about to be opened.
+ * @returns True when its history can safely be assumed empty.
+ */
+export function takeFreshlyCreated(sessionId: string): boolean {
+ return freshlyCreated.delete(sessionId);
+}
+
export const sessionApi = {
list: (agentId: string) => client.get<SessionListResponse>('/sessions/', { agent_id: agentId }),
- create: (body: CreateSessionRequest) => client.post<CreateSessionResponse>('/sessions/', body),
+ create: async (body: CreateSessionRequest) => {
+ const res = await client.post<CreateSessionResponse>('/sessions/', body);
+ freshlyCreated.add(res.session_id);
+ return res;
+ },
- update: (sessionId: string, agentId: string, body: UpdateSessionRequest) =>
- client.patch<SessionRecord>(`/sessions/${sessionId}`, body, { agent_id: agentId }),
+ /**
+ * Update a session's configuration.
+ *
+ * Returns 409 while a chat run holds the session — the agent
+ * snapshots its configuration at run start, so the change could not
+ * apply to the reply in flight. Pass `silent` for automatic writes
+ * the user did not initiate, where a toast would be noise.
+ */
+ update: (
+ sessionId: string,
+ agentId: string,
+ body: UpdateSessionRequest,
+ options?: { silent?: boolean },
+ ) =>
+ client.patch<SessionRecord>(`/sessions/${sessionId}`, body, { agent_id: agentId }, options),
delete: (sessionId: string, agentId: string) =>
client.delete(`/sessions/${sessionId}`, { agent_id: agentId }),
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 76ac5c874..ef4997d67 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -123,6 +123,12 @@ export interface SessionConfig {
/** Knowledge bases attached to this session + KB middleware parameters. */
knowledge_config: SessionKnowledgeConfig | null;
workspace_id: string;
+ /**
+ * Directory the session is focused on — absolute, or relative to the
+ * workspace root, and not confined to it. `null` means the root.
+ * Purely a viewing anchor; it does not move where tools execute.
+ */
+ cwd: string | null;
}
// TODO: update when Python side is finalised
@@ -190,6 +196,14 @@ export interface UpdateSessionRequest {
*/
knowledge_config?: SessionKnowledgeConfig | null;
permission_mode?: PermissionMode;
+ /**
+ * New working directory — absolute or relative to the workspace
+ * root, and not confined to it. PATCH semantics:
+ * - omit the field → leave unchanged
+ * - set to `null` → reset to the workspace root
+ * - set to a value → focus that directory
+ */
+ cwd?: string | null;
}
export interface SessionListResponse {
@@ -208,6 +222,68 @@ export interface ScheduleSessionsResponse {
total: number;
}
+// ─── Workspace files ──────────────────────────────────────────────────────────
+
+/** One entry in a workspace directory listing. */
+export interface DirectoryEntry {
+ name: string;
+ is_dir: boolean;
+ /** Always null for a directory, and for a file the backend could not stat. */
+ size_bytes: number | null;
+ /** Last modification time as a Unix timestamp. */
+ updated_at: number | null;
+}
+
+/** One directory level, plus the path it actually resolved to. */
+export interface DirectoryListing {
+ /**
+ * Absolute path of the directory that was listed. The only way to
+ * learn where a relative request landed — the workspace root is
+ * backend-dependent and unknowable client-side.
+ */
+ path: string;
+ entries: DirectoryEntry[];
+}
+
+/** Git state of one directory. */
+export interface GitStatus {
+ /** `null` on a detached HEAD. */
+ branch: string | null;
+ /** Full commit SHA, or `null` when the repository has no commits. */
+ head: string | null;
+ /**
+ * Commits ahead of the upstream. `null` means no upstream is
+ * configured, which is a different state from being level with one.
+ */
+ ahead: number | null;
+ behind: number | null;
+ /**
+ * Lines changed relative to HEAD. Untracked files contribute
+ * nothing — `git diff` does not see them — so a session that only
+ * created files reports zero here and a non-zero `untracked`.
+ */
+ insertions: number;
+ deletions: number;
+ /** File counts. */
+ staged: number;
+ unstaged: number;
+ untracked: number;
+ conflicted: number;
+}
+
+/** Where a session is pointed, and the git state of that place. */
+export interface WorkspaceStatus {
+ /** Absolute path of the workspace root; not derivable client-side. */
+ workdir: string;
+ /** Absolute path the session is focused on. Equals `workdir` when unset. */
+ cwd: string;
+ /**
+ * `null` when there is nothing to report — not a repository, git
+ * unavailable, timed out. The badge is hidden either way.
+ */
+ git: GitStatus | null;
+}
+
// ─── Team ─────────────────────────────────────────────────────────────────────
export interface TeamData {
@@ -247,20 +323,37 @@ export interface TeamDetailResponse {
members: TeamMemberInfo[];
}
+/**
+ * A session's unified status. `running` means a worker somewhere holds
+ * its run lease; the `awaiting_*` values mean nobody is running it but
+ * its stored context is parked on a pending tool call.
+ */
+export type SessionStatus = 'running' | 'idle' | 'awaiting_permission' | 'awaiting_external_result';
+
/**
* Per-session bundle returned by `GET /sessions/?agent_id=...`.
*
- * Bundles three pieces of information so the chat UI can render a
- * session without follow-up requests: the persisted record (incl.
- * `state`), whether a chat run is active, and — when the session
+ * Bundles what the chat UI needs to render a session without follow-up
+ * requests: the persisted record, its status, and — when the session
* participates in a team — the resolved team detail.
- *
- * Messages are intentionally separate (`GET /sessions/{id}/messages`)
- * since they paginate independently.
*/
export interface SessionView {
+ /**
+ * The record with the bulk of `state` stripped: `context`, `summary`
+ * and `tool_context` arrive cleared, since they hold the model's
+ * conversation and every file it has read. `permission_context` and
+ * `tasks_context` survive — the panels seed from them. Messages come
+ * from `GET /sessions/{id}/messages`.
+ */
session: SessionRecord;
+ /**
+ * @deprecated Use {@link status}. True only while a worker holds the
+ * run lease, which a session parked on a confirmation prompt does
+ * not — so this reads `false` for a session visibly waiting on you.
+ */
is_running: boolean;
+ /** Exactly one applies at a time, so one indicator renders it. */
+ status: SessionStatus;
team: TeamDetailResponse | null;
}
diff --git a/examples/web_ui/frontend/src/api/workspace.ts b/examples/web_ui/frontend/src/api/workspace.ts
index cd3a767c9..5379a8427 100644
--- a/examples/web_ui/frontend/src/api/workspace.ts
+++ b/examples/web_ui/frontend/src/api/workspace.ts
@@ -3,6 +3,8 @@ import type { UploadProgress } from './knowledgeBase';
import type {
AddFromLibraryResponse,
AddSkillRequest,
+ DirectoryListing,
+ WorkspaceStatus,
MCPClient,
MCPClientStatus,
Skill,
@@ -98,6 +100,36 @@ function uploadSkillXhr(
}
export const workspaceApi = {
+ /**
+ * List one directory level inside the session's workspace.
+ *
+ * `path` may be absolute or relative to the workspace root; empty
+ * lists the root itself. Not confined to the root — for a sandboxed
+ * backend the reachable filesystem is the sandbox, and for a local
+ * one the caller is already trusted with the host. The response
+ * echoes the resolved absolute path.
+ */
+ directories: (agentId: string, sessionId: string, path = '') =>
+ client.get<DirectoryListing>('/workspace/directories', {
+ agent_id: agentId,
+ session_id: sessionId,
+ path,
+ }),
+
+ /**
+ * Where the session is pointed, plus the git state of that place.
+ *
+ * `silent` because this is fetched on the UI's own schedule: git
+ * being unavailable is an ordinary answer, not something to raise a
+ * toast over.
+ */
+ status: (agentId: string, sessionId: string) =>
+ client.get<WorkspaceStatus>(
+ '/workspace/status',
+ { agent_id: agentId, session_id: sessionId },
+ { silent: true },
+ ),
+
mcp: {
list: (agentId: string, sessionId: string) =>
client.get<MCPClientStatus[]>('/workspace/mcp', {
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 2466652b6..40061e19f 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -4,12 +4,17 @@ import {
type Msg,
type ToolCallBlock,
} from '@agentscope-ai/agentscope/message';
-import React, { useMemo } from 'react';
+import { GitBranch } from 'lucide-react';
+import React, { useEffect, useMemo, useState } from 'react';
+import { Button } from '../ui/button';
+import { DiffStats } from './tool-renderers/_shared';
+import type { GitStatus } from '@/api';
import { ASMessageBubble } from '@/components/chat/ASMessageBubble.tsx';
import { ConfirmCard } from '@/components/chat/ConfirmCard.tsx';
import { FlipCard } from '@/components/chat/FlipCard.tsx';
import { TextInput } from '@/components/chat/TextInput.tsx';
+import { WorkingDirectoryDialog } from '@/components/dialog/WorkingDirectoryDialog';
import {
MessageScroller,
MessageScrollerButton,
@@ -18,12 +23,22 @@ import {
MessageScrollerProvider,
MessageScrollerViewport,
} from '@/components/ui/message-scroller.tsx';
+import { Spinner } from '@/components/ui/spinner';
import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n';
import { cn } from '@/lib/utils';
+/** How long a load may run before it is worth showing a spinner. */
+const SPINNER_DELAY_MS = 150;
+
interface ChatContentProps {
msgs: Msg[];
+ /**
+ * Whether the history for the currently selected session is still on
+ * the wire. Takes precedence over {@link msgs}, which still holds the
+ * *previous* session's messages until the fetch effect clears them.
+ */
+ loading?: boolean;
/**
* Reply lifecycle phase from ``useMessages`` — forwarded to
* ``TextInput`` so the single send / stop button can pick its
@@ -54,10 +69,23 @@ interface ChatContentProps {
allowedInputTypes: string[];
/** @see TextInputProps.fileProcessor */
fileProcessor: (file: File) => Promise<ContentBlock | null>;
+ /** Agent owning the open session — drives the directory picker. */
+ agentId: string | null;
+ /** The open session, whose working directory the picker edits. */
+ sessionId: string | null;
+ /** Current working directory, relative to the workspace root. */
+ cwd: string | null;
+ /** Persists a new working directory. */
+ onCwdChange: (cwd: string | null) => void | Promise<void>;
+ /** Git state of {@link cwd}; `null` hides the branch badge entirely. */
+ git?: GitStatus | null;
+ /** Re-reads the git state, since nothing polls for it. */
+ onRefreshGit?: () => void | Promise<void>;
}
const ChatContentComponent: React.FC<ChatContentProps> = ({
msgs,
+ loading = false,
phase,
disabled,
onSend,
@@ -68,9 +96,32 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
footerSlot,
allowedInputTypes,
fileProcessor,
+ agentId,
+ sessionId,
+ cwd,
+ onCwdChange,
+ git,
+ onRefreshGit,
}) => {
const { t } = useTranslation();
- const isEmpty = msgs.length === 0;
+ // Only a session that finished loading with nothing in it is empty.
+ // Treating "no messages yet" as empty would flash the greeting over
+ // every session that does have history.
+ const isEmpty = !loading && msgs.length === 0;
+
+ // A spinner that appears and vanishes inside a couple of frames reads
+ // as a flicker, not as feedback — so hold it back until the load has
+ // gone on long enough to be worth reporting. The gap renders blank,
+ // which is invisible at this duration.
+ const [showSpinner, setShowSpinner] = useState(false);
+ useEffect(() => {
+ if (!loading) {
+ setShowSpinner(false);
+ return;
+ }
+ const timer = setTimeout(() => setShowSpinner(true), SPINNER_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [loading]);
const toConfirmedToolCalls = useMemo(() => {
if (msgs.length === 0) return [];
@@ -91,7 +142,11 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
className,
)}
>
- {isEmpty ? (
+ {loading ? (
+ <div className="flex flex-1 w-full items-center justify-center">
+ {showSpinner ? <Spinner className="size-5 text-muted-foreground" /> : null}
+ </div>
+ ) : isEmpty ? (
<span className="text-center text-4xl font-light tracking-[-0.035em] text-foreground mb-2">
{t('chat.greeting')}
</span>
@@ -116,38 +171,88 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
</MessageScrollerProvider>
)}
- <div className="relative min-w-full max-w-full w-full">
- <FlipCard
- visible={toConfirmedToolCalls.length > 0 || footerSlot !== null}
- className="absolute bottom-full left-0 right-0 mb-2 z-50"
- >
- {toConfirmedToolCalls.length > 0 ? (
- <ConfirmCard
- toolCall={toConfirmedToolCalls[0].toolCall}
- onUserConfirm={async (confirm, rules) => {
- onUserConfirm(
- toConfirmedToolCalls[0].toolCall,
- confirm,
- toConfirmedToolCalls[0].replyId,
- rules,
- );
- }}
- />
- ) : (
- footerSlot
- )}
- </FlipCard>
- <TextInput
- className="min-w-full max-w-full w-full"
- onSend={onSend}
- disabled={disabled}
- autoComplete={autoComplete}
- allowedInputTypes={allowedInputTypes}
- fileProcessor={fileProcessor}
- phase={phase}
- onInterrupt={onInterrupt}
- />{' '}
- </div>
+ {loading ? null : (
+ <div className="relative min-w-full max-w-full w-full">
+ <FlipCard
+ visible={toConfirmedToolCalls.length > 0 || footerSlot !== null}
+ className="absolute bottom-full left-0 right-0 mb-2 z-50"
+ >
+ {toConfirmedToolCalls.length > 0 ? (
+ <ConfirmCard
+ toolCall={toConfirmedToolCalls[0].toolCall}
+ onUserConfirm={async (confirm, rules) => {
+ onUserConfirm(
+ toConfirmedToolCalls[0].toolCall,
+ confirm,
+ toConfirmedToolCalls[0].replyId,
+ rules,
+ );
+ }}
+ />
+ ) : (
+ footerSlot
+ )}
+ </FlipCard>
+ {/* Concentric radii: the pill stays rounded-[28px] on all four
+ corners and floats on this surface, whose own radius is
+ 28 + the 4px padding. Matching them is what keeps the two
+ edges parallel — a plain rectangle here would show the
+ pill's corners cutting into it. */}
+ <TextInput
+ className="min-w-full max-w-full w-full rounded-[32px] bg-muted p-1"
+ onSend={onSend}
+ disabled={disabled}
+ autoComplete={autoComplete}
+ allowedInputTypes={allowedInputTypes}
+ fileProcessor={fileProcessor}
+ phase={phase}
+ onInterrupt={onInterrupt}
+ headerSlot={
+ <div className="flex w-full items-center justify-between px-2 py-1 text-sm text-muted-foreground">
+ <WorkingDirectoryDialog
+ agentId={agentId}
+ sessionId={sessionId}
+ value={cwd}
+ onChange={onCwdChange}
+ />
+ {git && (
+ <Button
+ className="font-mono"
+ variant="secondary"
+ size="sm"
+ onClick={() => void onRefreshGit?.()}
+ title={t('workdir.gitTooltip', {
+ staged: git.staged,
+ unstaged: git.unstaged,
+ untracked: git.untracked,
+ })}
+ >
+ <GitBranch />
+ {/* A detached HEAD has no branch to name, so
+ fall back to the commit it sits on. The
+ server sends no git at all when it has
+ neither. */}
+ {git.branch ?? git.head?.slice(0, 7)}
+ {git.ahead !== null && git.ahead > 0 && (
+ <span className="text-xs">↑{git.ahead}</span>
+ )}
+ {git.behind !== null && git.behind > 0 && (
+ <span className="text-xs">↓{git.behind}</span>
+ )}
+ {/* Renders nothing when both are zero, so a
+ clean tree shows just the branch. */}
+ <DiffStats
+ className="text-xs font-mono"
+ insertions={git.insertions}
+ deletions={git.deletions}
+ />
+ </Button>
+ )}
+ </div>
+ }
+ />
+ </div>
+ )}
</div>
);
};
diff --git a/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx b/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx
index 0b73804f1..4b201eedd 100644
--- a/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ConfirmCard.tsx
@@ -65,7 +65,10 @@ export function ConfirmCard({
<div className="bg-muted ring ring-border rounded-[28px] w-full px-6 py-5 space-y-4 text-sm overflow-hidden">
<div className="flex flex-col gap-y-2 max-w-full">
<strong className="text-secondary-foreground">{getDisplayName(toolCall, t)}</strong>
- <div className="px-4 py-2 bg-white rounded-sm max-w-full">
+ {/* Capped so a long tool input (raw JSON for MCP tools) cannot
+ grow the card past the viewport — it floats above the
+ composer and is out of flow, so nothing else clips it. */}
+ <div className="px-4 py-2 bg-white rounded-sm max-w-full max-h-[200px] overflow-y-auto">
{renderConfirmBody(toolCall, t)}
</div>
</div>
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index d6c85fa64..37fcda415 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -84,6 +84,18 @@ interface TextInputProps {
*/
phase?: ReplyPhase;
onInterrupt?: () => void;
+ /**
+ * Content rendered directly above the input pill, inside the outer
+ * wrapper that {@link className} styles (e.g. the working directory
+ * and git status).
+ *
+ * The pill keeps all four of its corners, so the two only read as one
+ * surface if the caller gives that wrapper a background and a radius
+ * concentric with the pill's — outer radius = 28px + the wrapper's
+ * padding. Anything less and the pill's top corners cut into the
+ * header's edges.
+ */
+ headerSlot?: React.ReactNode;
}
export interface TextInputRef {
@@ -127,6 +139,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
fileProcessor,
phase = 'idle',
onInterrupt,
+ headerSlot,
},
ref,
) => {
@@ -312,6 +325,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
return (
<div className={cn('flex flex-col', className)}>
+ {headerSlot}
<div
id="tour-chat-input"
className="flex w-full flex-col rounded-[28px] border bg-background px-2"
diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
index 8918df3eb..4d185519b 100644
--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/_shared.tsx
@@ -199,10 +199,18 @@ export function FramedFileBody({ filePath, children }: { filePath?: string; chil
* Compact ``+N -M`` badge used in tool call headers for Edit / Write to show
* how many lines were inserted and deleted.
*/
-export function DiffStats({ insertions, deletions }: { insertions: number; deletions: number }) {
+export function DiffStats({
+ insertions,
+ deletions,
+ className,
+}: {
+ insertions: number;
+ deletions: number;
+ className?: string;
+}) {
if (insertions === 0 && deletions === 0) return null;
return (
- <div className="flex items-center gap-0.5">
+ <div className={cn('flex items-center gap-0.5', className)}>
<div className="flex items-center text-emerald-600 dark:text-emerald-400">
<Plus className="size-2.5 stroke-2" />
{formatNumber(insertions)}
diff --git a/examples/web_ui/frontend/src/components/dialog/WorkingDirectoryDialog.tsx b/examples/web_ui/frontend/src/components/dialog/WorkingDirectoryDialog.tsx
new file mode 100644
index 000000000..c606121c2
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/dialog/WorkingDirectoryDialog.tsx
@@ -0,0 +1,348 @@
+import {
+ ChevronDown,
+ CircleAlert,
+ CheckCircle,
+ CornerLeftUp,
+ File,
+ Folder,
+ FolderOpen,
+ Home,
+ Loader2,
+ CornerDownLeft,
+} from 'lucide-react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '../ui/input-group';
+import type { DirectoryEntry } from '@/api';
+import { workspaceApi } from '@/api';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty';
+import { Spinner } from '@/components/ui/spinner';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useTranslation } from '@/i18n/useI18n';
+import { formatApiErrorForAlert } from '@/lib/api-error';
+
+interface WorkingDirectoryDialogProps {
+ agentId: string | null;
+ sessionId: string | null;
+ /**
+ * The session's current working directory. Absolute, or relative to
+ * the workspace root; `null` is the root itself.
+ */
+ value: string | null;
+ /**
+ * Called with the newly picked directory. Rejections are the caller's
+ * to surface; the dialog only closes once the promise settles.
+ */
+ onChange: (cwd: string | null) => void | Promise<void>;
+ disabled?: boolean;
+ className?: string;
+}
+
+/** The last segment of a path, which is what a folder is called. */
+function basename(path: string): string {
+ const trimmed = path.replace(/\/+$/, '');
+ const cut = trimmed.lastIndexOf('/');
+ return cut === -1 ? trimmed : trimmed.slice(cut + 1);
+}
+
+/**
+ * A folder picker for the session's working directory.
+ *
+ * Hands back a **path**, never a file — nothing is uploaded and nothing
+ * is read. Only directories are listed, since a file is never a valid
+ * answer.
+ *
+ * Browsing is not confined to the workspace root: the picker walks
+ * wherever `GET /workspace/directories` can reach, which is the sandbox
+ * on a container backend and the host on a local one. Because the root
+ * is backend-dependent, the browser never knows where it is until the
+ * server says so — hence every listing is addressed by the absolute path
+ * the previous response echoed back, and only the initial "open at the
+ * session's directory" request uses the stored (possibly relative) value.
+ *
+ * A dialog rather than a popover: finding a folder anywhere on the
+ * filesystem is a task, not a quick toggle, so it earns the room and the
+ * deliberate dismissal.
+ *
+ * @param agentId - Agent owning the session. `null` disables the trigger.
+ * @param sessionId - Session whose workspace is browsed.
+ * @param value - Current working directory, or `null` for the root.
+ * @param onChange - Receives the picked directory.
+ * @param disabled - Locks the trigger.
+ * @param className - Extra classes for the trigger button.
+ * @returns The trigger button plus its dialog.
+ */
+export function WorkingDirectoryDialog({
+ agentId,
+ sessionId,
+ value,
+ onChange,
+ disabled = false,
+ className,
+}: WorkingDirectoryDialogProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ // The answer, and the single source of truth: whatever the input
+ // shows is what Confirm submits. Browsing is just another way to fill
+ // it in. Splitting this into "the browsed path" and "the typed path"
+ // is what let an edited-but-unsubmitted input silently save the old
+ // value instead.
+ const [path, setPath] = useState('');
+ // The listing currently on screen, and the path it came from — which
+ // trails `path` while the user is mid-edit.
+ const [listedPath, setListedPath] = useState<string | null>(null);
+ const [entries, setEntries] = useState<DirectoryEntry[]>([]);
+ // Starts true because the effect below runs after the first paint —
+ // leaving it false would flash an empty listing over a directory that
+ // is about to arrive.
+ const [loading, setLoading] = useState(true);
+ // Whatever went wrong last, listing or saving. Shown in place of the
+ // list — one home for both, so nothing is reported twice.
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ // Bumped by every browse, so an overtaken listing cannot land.
+ const reqId = useRef(0);
+
+ const load = useCallback(
+ async (target: string) => {
+ // Only the newest browse may write: a slow parent directory
+ // answering after a fast child would silently bounce the user
+ // back up a level.
+ const id = ++reqId.current;
+ if (!agentId || !sessionId) {
+ setLoading(false);
+ return;
+ }
+ setLoading(true);
+ setError(null);
+ try {
+ const listing = await workspaceApi.directories(agentId, sessionId, target);
+ if (id !== reqId.current) return;
+ // Files are listed but not selectable — a directory with its
+ // files hidden is hard to recognise, and "empty" would be a
+ // lie for a folder that is merely all files. Order is the
+ // backend's; the icon already says which is which.
+ setEntries(listing.entries);
+ // Adopt the resolved path: the server normalises `..` and
+ // turns a relative request absolute, so this is also how the
+ // input learns where the workspace root actually is.
+ setPath(listing.path);
+ setListedPath(listing.path);
+ } catch (e) {
+ if (id !== reqId.current) return;
+ // `path` is left alone — it is what the user asked for, and
+ // blanking it would erase what they typed. `listedPath`
+ // staying null is what disables Confirm.
+ setListedPath(null);
+ setEntries([]);
+ // Inline, not a toast: the dialog is the only thing the user
+ // is looking at, and a directory that has moved is a normal
+ // outcome of browsing a workspace an agent is changing under
+ // you.
+ setError(formatApiErrorForAlert(e));
+ } finally {
+ if (id === reqId.current) setLoading(false);
+ }
+ },
+ [agentId, sessionId],
+ );
+
+ // Re-open always restarts from the session's committed directory, so
+ // a cancelled browse does not leak into the next one.
+ useEffect(() => {
+ if (open) void load(value ?? '');
+ }, [open, value, load]);
+
+ const handleConfirm = async () => {
+ setSaving(true);
+ setError(null);
+ try {
+ await onChange(path);
+ setOpen(false);
+ } catch (e) {
+ // Most likely a 409 — the session started running while the
+ // dialog was open. Staying open with the reason on screen beats
+ // closing as if it worked. The list is fine, so this is the one
+ // failure the Alert still has to carry.
+ setError(formatApiErrorForAlert(e));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const label = value ? basename(value) : t('workdir.root');
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={disabled || !agentId || !sessionId}
+ className={className}
+ title={value ?? t('workdir.root')}
+ >
+ <Folder />
+ <span className="truncate max-w-40">{label}</span>
+ <ChevronDown className="text-muted-foreground" />
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t('workdir.title')}</DialogTitle>
+ <DialogDescription>{t('workdir.description')}</DialogDescription>
+ </DialogHeader>
+
+ {/* `min-w-0` all the way down: without it a long entry name
+ widens this column, and the dialog with it, instead of
+ being elided inside its own row. */}
+ <div className="flex min-w-0 flex-col gap-y-2">
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ void load(path);
+ }}
+ >
+ <InputGroup>
+ <InputGroupInput
+ value={path}
+ spellCheck={false}
+ className="font-mono text-[0.8rem]! tracking-tighter"
+ placeholder={t('workdir.pathPlaceholder')}
+ onChange={(e) => {
+ setPath(e.target.value);
+ // The failed save was for a different path;
+ // the listing keeps its own error until the
+ // next load replaces it.
+ setError(null);
+ }}
+ />
+ <InputGroupAddon>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InputGroupButton
+ type="button"
+ onClick={() => void load('')}
+ >
+ <Home />
+ </InputGroupButton>
+ </TooltipTrigger>
+ <TooltipContent>{t('workdir.root')}</TooltipContent>
+ </Tooltip>
+ </InputGroupAddon>
+ <InputGroupAddon align="inline-end">
+ {/* Submits the form, so clicking and pressing
+ Enter go through the same handler. */}
+ <InputGroupButton type="submit">
+ <CornerDownLeft />
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ </form>
+ <div className="h-[50vh] min-w-0 overflow-y-auto border rounded-[1rem] p-1">
+ {loading ? (
+ <div className="flex h-full items-center justify-center">
+ <Spinner className="text-muted-foreground" />
+ </div>
+ ) : error ? (
+ <Empty className="h-full border-0 p-4">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FolderOpen />
+ </EmptyMedia>
+ <EmptyTitle>{t('workdir.errorTitle')}</EmptyTitle>
+ {/* The title says a listing failed; this says
+ why — missing, a file, unreadable. */}
+ <EmptyDescription className="break-all">
+ {error}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <>
+ {/* Always offered: the server resolves `..` against
+ wherever we are, so there is no floor to
+ special-case. */}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 font-normal"
+ onClick={() => void load(`${listedPath ?? ''}/..`)}
+ >
+ <CornerLeftUp className="size-3.5 shrink-0" />
+ {t('workdir.parent')}
+ </Button>
+ {entries.length === 0 ? (
+ <p className="px-2 py-3 text-center text-xs text-muted-foreground">
+ {t('workdir.empty')}
+ </p>
+ ) : (
+ entries.map((entry) => (
+ <Button
+ key={entry.name}
+ variant="ghost"
+ size="sm"
+ // A file is context, never an answer: it is
+ // listed so the folder is recognisable, but
+ // only a directory can be picked.
+ disabled={!entry.is_dir}
+ // `min-w-0` is what makes the child's
+ // `truncate` work: a flex item defaults to
+ // min-width:auto, so a long name widens the
+ // row instead of eliding inside it.
+ className="w-full min-w-0 justify-start gap-2 font-normal"
+ onClick={() =>
+ void load(`${listedPath ?? ''}/${entry.name}`)
+ }
+ >
+ {entry.is_dir ? (
+ <Folder className="size-3.5 shrink-0" />
+ ) : (
+ <File className="size-3.5 shrink-0" />
+ )}
+ <span className="min-w-0 truncate">{entry.name}</span>
+ </Button>
+ ))
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setOpen(false)} disabled={saving}>
+ <CircleAlert className="size-3.5" />
+ {t('common.cancel')}
+ </Button>
+ <Button
+ onClick={() => void handleConfirm()}
+ disabled={saving || listedPath !== path}
+ title={listedPath === path ? undefined : t('workdir.pressEnter')}
+ >
+ {saving ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <CheckCircle className="size-3.5" />
+ )}
+ {t('common.confirm')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
index 8930b46a6..7cf506802 100644
--- a/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
+++ b/examples/web_ui/frontend/src/components/panel/PanelDock.tsx
@@ -13,7 +13,7 @@ import { Separator } from '@/components/ui/separator';
* Identifier for a dockable panel. Used both as the React key and to
* look its descriptor up in {@link PanelDockProps.panels}.
*/
-export type PanelKey = 'plan' | 'mcp' | 'skill' | 'permission' | 'knowledge';
+export type PanelKey = 'plan' | 'mcp' | 'skill' | 'permission' | 'knowledge' | 'team';
/**
* The presentation of a single panel: header chrome plus its already
diff --git a/examples/web_ui/frontend/src/components/panel/TeamPanel.tsx b/examples/web_ui/frontend/src/components/panel/TeamPanel.tsx
new file mode 100644
index 000000000..68e1fa3ef
--- /dev/null
+++ b/examples/web_ui/frontend/src/components/panel/TeamPanel.tsx
@@ -0,0 +1,142 @@
+import { Bot, Crown, UsersRound } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+
+import type { AgentView, TeamDetailResponse, TeamMemberInfo } from '@/api';
+import { PanelEmpty } from '@/components/panel/PanelEmpty';
+import { Button } from '@/components/ui/button';
+import { useTranslation } from '@/i18n/useI18n';
+import { cn } from '@/lib/utils';
+
+interface TeamPanelProps {
+ /**
+ * Resolved team detail (leader + members), or `null` when the open
+ * session is not part of a team.
+ */
+ team: TeamDetailResponse | null;
+ /**
+ * The session currently shown in the chat area — drives which row is
+ * highlighted as active.
+ */
+ currentSessionId: string | null;
+}
+
+/**
+ * Dock panel listing a team's leader and members, each row navigating
+ * to that participant's session.
+ *
+ * Clicking the leader navigates to `/chat/<leaderAgentId>/<leaderSessionId>`,
+ * dropping the URL's optional `:memberId` slot so the chat area falls
+ * back to the leader session. Clicking a member appends that slot
+ * instead — the outer URL segments stay put, so the page sidebar does
+ * not collapse and only the chat area reroutes.
+ *
+ * Both ids come from the `team` prop, so the caller only has to say
+ * which session is currently open.
+ *
+ * Renders without its own header or border — the surrounding `Panel`
+ * chrome from `PanelDock` provides those.
+ *
+ * @param team - Resolved team detail, or `null` when there is no team.
+ * @param currentSessionId - Session shown in the chat area.
+ * @returns The panel body.
+ */
+export function TeamPanel({ team, currentSessionId }: TeamPanelProps) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+
+ if (!team) {
+ return (
+ <PanelEmpty
+ icon={UsersRound}
+ title={t('panel.team.emptyTitle')}
+ description={t('panel.team.emptyDescription')}
+ />
+ );
+ }
+
+ const leaderAgentId = team.leader_agent?.id ?? null;
+ const leaderSessionId = team.team.session_id;
+
+ const goToLeader = () => {
+ if (!leaderAgentId) return;
+ navigate(`/chat/${leaderAgentId}/${leaderSessionId}`);
+ };
+
+ const goToMember = (memberAgentId: string) => {
+ if (!leaderAgentId) return;
+ navigate(`/chat/${leaderAgentId}/${leaderSessionId}/${memberAgentId}`);
+ };
+
+ const renderRow = (
+ key: string,
+ icon: React.ReactNode,
+ label: string,
+ isActive: boolean,
+ disabled: boolean,
+ onClick: () => void,
+ ) => (
+ <li key={key}>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={disabled}
+ onClick={onClick}
+ className={cn(
+ 'w-full justify-start gap-2 font-normal',
+ isActive && 'bg-accent text-accent-foreground',
+ )}
+ >
+ {icon}
+ <span className="truncate">{label}</span>
+ </Button>
+ </li>
+ );
+
+ const renderLeader = (leader: AgentView) =>
+ renderRow(
+ leader.id,
+ <Crown className="size-3.5 shrink-0" />,
+ leader.data.name,
+ currentSessionId === leaderSessionId,
+ false,
+ goToLeader,
+ );
+
+ const renderMember = (member: TeamMemberInfo) =>
+ renderRow(
+ member.agent.id,
+ <Bot className="size-3.5 shrink-0" />,
+ member.agent.data.name,
+ member.session_id === currentSessionId,
+ member.session_id === null,
+ () => goToMember(member.agent.id),
+ );
+
+ return (
+ <div className="flex flex-col flex-1 min-h-0 gap-y-3 text-sm overflow-y-auto">
+ <div className="shrink-0 px-2">
+ <span className="truncate text-sm font-medium">{team.team.data.name}</span>
+ </div>
+
+ {team.leader_agent && (
+ <section className="flex flex-col gap-y-0.5">
+ <span className="px-2 text-xs text-muted-foreground">{t('common.leader')}</span>
+ <ul className="flex flex-col">{renderLeader(team.leader_agent)}</ul>
+ </section>
+ )}
+
+ <section className="flex flex-col gap-y-0.5">
+ <span className="px-2 text-xs text-muted-foreground">
+ {t('panel.team.membersHeading')}
+ </span>
+ {team.members.length === 0 ? (
+ <p className="px-2 py-1 text-xs text-muted-foreground">
+ {t('panel.team.noMembers')}
+ </p>
+ ) : (
+ <ul className="flex flex-col">{team.members.map(renderMember)}</ul>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
index 19065da2a..4b99360cc 100644
--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
@@ -210,6 +210,12 @@ interface Props {
selectedTTSModel?: TTSModelConfig | null;
/** Called when the user picks a TTS model+voice or disables TTS. */
onTTSChange?: (config: TTSModelConfig | null) => void;
+ /**
+ * Locks the trigger while a session config write is in flight, so a
+ * second edit cannot race the first. The trigger is also locked
+ * whenever no primary model is selected.
+ */
+ disabled?: boolean;
}
/**
@@ -229,6 +235,7 @@ export function ModelParametersPopover({
onFallbackChange,
selectedTTSModel,
onTTSChange,
+ disabled: locked = false,
}: Props) {
const [values, setValues] = useState<Record<string, unknown>>({});
const { t } = useTranslation();
@@ -265,7 +272,7 @@ export function ModelParametersPopover({
});
};
- const disabled = !selectedModel;
+ const disabled = locked || !selectedModel;
const hasFallbackOptions = Object.keys(groups).length > 0;
return (
diff --git a/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx b/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx
deleted file mode 100644
index eb6ee488e..000000000
--- a/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { Bot, Crown } from 'lucide-react';
-import { useNavigate } from 'react-router-dom';
-
-import type { TeamDetailResponse, TeamMemberInfo, AgentView } from '@/api';
-import {
- Sidebar,
- SidebarContent,
- SidebarFooter,
- SidebarGroup,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarHeader,
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
-} from '@/components/ui/sidebar';
-import { useTranslation } from '@/i18n/useI18n';
-
-interface TeamSidebarProps {
- /** Resolved team detail (leader + members) — drives all rendering. */
- team: TeamDetailResponse;
- /**
- * The session id currently shown in the chat area. Used both for
- * highlighting the active row and for deciding whether the row
- * being clicked is already the current one.
- */
- currentSessionId: string;
-}
-
-/**
- * Secondary sidebar shown next to the chat area whenever the open
- * session participates in a team.
- *
- * Built on the shared shadcn `Sidebar` primitives so it visually
- * matches the main page sidebar (same paddings, item heights,
- * active-row treatment, etc.). Renders the leader at the top
- * followed by every member; all rows are clickable.
- *
- * Clicking the leader row navigates to
- * `/chat/<leaderAgentId>/<leaderSessionId>` (drops the URL's
- * optional `:memberId` slot so the chat area falls back to the
- * leader session). Clicking a member row navigates to
- * `/chat/<leaderAgentId>/<leaderSessionId>/<memberAgentId>` — the
- * outer URL slots stay the same so the main page sidebar does not
- * collapse; only the chat area reroutes to the member's session.
- *
- * Both `leaderAgentId` and `leaderSessionId` are derived from the
- * passed `team` prop, so the parent only needs to know which
- * session is currently active.
- *
- * @param team - Resolved team detail.
- * @param currentSessionId - Session id currently shown in the chat
- * area; used to drive row highlighting.
- * @returns A vertical sidebar element.
- */
-export function TeamSidebar({ team, currentSessionId }: TeamSidebarProps) {
- const { t } = useTranslation();
- const navigate = useNavigate();
-
- const leaderAgentId = team.leader_agent?.id ?? null;
- const leaderSessionId = team.team.session_id;
-
- const goToLeader = () => {
- if (!leaderAgentId) return;
- navigate(`/chat/${leaderAgentId}/${leaderSessionId}`);
- };
-
- const goToMember = (memberAgentId: string) => {
- if (!leaderAgentId) return;
- navigate(`/chat/${leaderAgentId}/${leaderSessionId}/${memberAgentId}`);
- };
-
- const renderLeader = (leader: AgentView) => (
- <SidebarMenuItem>
- <SidebarMenuButton isActive={currentSessionId === leaderSessionId} onClick={goToLeader}>
- <Crown />
- <span className="truncate">{leader.data.name}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
-
- const renderMember = (member: TeamMemberInfo) => (
- <SidebarMenuItem key={member.agent.id}>
- <SidebarMenuButton
- isActive={member.session_id === currentSessionId}
- disabled={member.session_id === null}
- onClick={() => goToMember(member.agent.id)}
- >
- <Bot />
- <span className="truncate">{member.agent.data.name}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
-
- return (
- <Sidebar collapsible="none" className="w-56 border-r">
- <SidebarHeader>
- <div className="flex flex-col gap-y-1 px-2 py-1">
- <span className="text-muted-foreground text-xs uppercase tracking-wide">
- {t('common.team')}
- </span>
- <span className="truncate text-sm font-medium">{team.team.data.name}</span>
- </div>
- </SidebarHeader>
- <SidebarContent>
- {team.leader_agent && (
- <SidebarGroup>
- <SidebarGroupLabel>{t('common.leader')}</SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>{renderLeader(team.leader_agent)}</SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- )}
-
- <SidebarGroup>
- <SidebarGroupLabel>{t('team-sidebar.membersHeading')}</SidebarGroupLabel>
- <SidebarGroupContent>
- {team.members.length === 0 ? (
- <p className="px-3 py-2 text-xs text-muted-foreground">
- {t('team-sidebar.noMembers')}
- </p>
- ) : (
- <SidebarMenu>{team.members.map(renderMember)}</SidebarMenu>
- )}
- </SidebarGroupContent>
- </SidebarGroup>
- </SidebarContent>
- <SidebarFooter />
- </Sidebar>
- );
-}
diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.ts
index 29467317b..781107d23 100644
--- a/examples/web_ui/frontend/src/hooks/useMessages.ts
+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts
@@ -13,7 +13,7 @@ import type { Msg, ContentBlock } from '@agentscope-ai/agentscope/message';
import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';
import { useState, useCallback, useRef, useEffect } from 'react';
-import { sessionApi } from '@/api';
+import { sessionApi, takeFreshlyCreated } from '@/api';
import { chatApi } from '@/api';
import { useAudioManager } from '@/context/AudioContext';
@@ -102,7 +102,9 @@ const INTERRUPT_TIMEOUT_MS = 10_000;
* skip.
* @param sessionId - The session to subscribe. ``null`` to skip.
* @returns Object with ``msgs``, ``loading``, ``phase``, ``error``,
- * ``send``, ``onUserConfirm``, and ``abort``.
+ * ``send``, ``onUserConfirm``, and ``abort``. ``loading`` stays true
+ * until the history for the *current* ``(agentId, sessionId)`` has
+ * landed, so ``msgs`` must not be rendered while it is set.
*/
export function useMessages(
agentId: string | null,
@@ -125,7 +127,12 @@ export function useMessages(
},
) {
const [msgs, setMsgs] = useState<Msg[]>([]);
- const [loading, setLoading] = useState(false);
+ // The (agent, session) pair `msgs` actually belongs to. Loading is
+ // derived from it rather than set inside the fetch effect: an effect
+ // runs *after* the render that changed `sessionId`, so a flag it owns
+ // is still `false` for one frame — long enough to paint the empty
+ // state over a session that does have messages.
+ const [loadedKey, setLoadedKey] = useState<string | null>(null);
const [phase, setPhase] = useState<ReplyPhase>('idle');
const [error, setError] = useState<Error | null>(null);
// Pending subagent HITL cards projected onto this (leader) session.
@@ -252,35 +259,50 @@ export function useMessages(
let cancelled = false;
(async () => {
- // 1. Fetch persisted history
- setLoading(true);
- try {
- const { messages, is_running } = await sessionApi.messages(sessionId, agentId);
- if (cancelled) return;
- msgsRef.current = messages;
- // If a reply is in flight (running on a worker) OR the
- // tail msg is parked on a pending tool_call (awaiting
- // user confirmation / external execution), initialise the
- // phase to ``streaming`` so the interrupt button is
- // available immediately — otherwise a fresh page load
- // while parked leaves the UI stuck on ``idle`` with no
- // way to abort.
- const tail = messages[messages.length - 1];
- if (is_running || hasPendingToolCall(tail)) {
- setPhase('streaming');
- if (hasPendingToolCall(tail)) {
- // Prime the ref so continuation events (which
- // arrive without a fresh REPLY_START) apply to
- // the right msg.
- currentReplyRef.current = tail ?? null;
+ // 1. Fetch persisted history — unless this tab just created the
+ // session, in which case there is provably none.
+ if (takeFreshlyCreated(sessionId)) {
+ if (!cancelled) setLoadedKey(`${agentId}:${sessionId}`);
+ } else {
+ try {
+ const { messages, is_running } = await sessionApi.messages(sessionId, agentId);
+ if (cancelled) return;
+ msgsRef.current = messages;
+ // If a reply is in flight (running on a worker) OR the
+ // tail msg is parked on a pending tool_call (awaiting
+ // user confirmation / external execution), initialise the
+ // phase to ``streaming`` so the interrupt button is
+ // available immediately — otherwise a fresh page load
+ // while parked leaves the UI stuck on ``idle`` with no
+ // way to abort.
+ const tail = messages[messages.length - 1];
+ if (is_running || hasPendingToolCall(tail)) {
+ setPhase('streaming');
+ if (hasPendingToolCall(tail)) {
+ // Prime the ref so continuation events (which
+ // arrive without a fresh REPLY_START) apply to
+ // the right msg.
+ currentReplyRef.current = tail ?? null;
+ }
}
+ // Published synchronously, not through `scheduleUpdate`:
+ // its requestAnimationFrame batching exists for
+ // high-frequency streaming deltas, and deferring here
+ // would let `loadedKey` below clear `loading` a frame
+ // before the messages land — painting the empty-session
+ // greeting over a conversation that does have history.
+ // Both setters now land in the same React batch.
+ setMsgs([...msgsRef.current]);
+ } catch (e) {
+ if (!cancelled) setError(e as Error);
+ return;
+ } finally {
+ // Marks the load done whether it succeeded or threw —
+ // an error surfaces through `error`, and leaving
+ // `loading` stuck on would hide it behind a spinner
+ // forever.
+ if (!cancelled) setLoadedKey(`${agentId}:${sessionId}`);
}
- scheduleUpdate();
- } catch (e) {
- if (!cancelled) setError(e as Error);
- return;
- } finally {
- if (!cancelled) setLoading(false);
}
// 2. Open SSE long connection for live events
@@ -476,6 +498,14 @@ export function useMessages(
[agentId, sessionId],
);
+ // True from the very first render after `sessionId` changes, because
+ // it compares props against what was fetched rather than tracking a
+ // flag an effect has yet to flip. `msgs` is still the previous
+ // session's until the effect clears it, so consumers must render the
+ // loading state in preference to `msgs`.
+ const loading =
+ agentId !== null && sessionId !== null && loadedKey !== `${agentId}:${sessionId}`;
+
return {
msgs,
loading,
diff --git a/examples/web_ui/frontend/src/hooks/useSessions.ts b/examples/web_ui/frontend/src/hooks/useSessions.ts
index e7b788104..8e24c2ab6 100644
--- a/examples/web_ui/frontend/src/hooks/useSessions.ts
+++ b/examples/web_ui/frontend/src/hooks/useSessions.ts
@@ -20,18 +20,30 @@ export function useSessions(agentId: string | null) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
- const refetch = useCallback(async () => {
+ /**
+ * Reload the session list.
+ *
+ * Also returns the fresh list, so a caller reacting to an event can
+ * act on it immediately — reading the `sessions` state right after
+ * awaiting would still see the pre-update value from its closure.
+ *
+ * @returns The reloaded views, or an empty array when there is no
+ * agent or the request failed.
+ */
+ const refetch = useCallback(async (): Promise<SessionView[]> => {
if (!agentId) {
setSessions([]);
- return;
+ return [];
}
setLoading(true);
setError(null);
try {
const res = await sessionApi.list(agentId);
setSessions(res.sessions);
+ return res.sessions;
} catch (e) {
setError(e as Error);
+ return [];
} finally {
setLoading(false);
}
diff --git a/examples/web_ui/frontend/src/hooks/useWorkspaceStatus.ts b/examples/web_ui/frontend/src/hooks/useWorkspaceStatus.ts
new file mode 100644
index 000000000..9769bec4c
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useWorkspaceStatus.ts
@@ -0,0 +1,63 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { workspaceApi } from '@/api';
+import type { WorkspaceStatus } from '@/api';
+
+/**
+ * Tracks where a session is pointed and the git state of that place.
+ *
+ * Not polled. Running git is a subprocess — a round trip too on a
+ * sandboxed backend — and the two things that change the answer are both
+ * observable: the user moving `cwd`, and a reply finishing. Callers
+ * refetch on the latter and pass `cwd` so the former re-runs on its own.
+ *
+ * @param agentId - Agent owning the session. `null` clears the state.
+ * @param sessionId - The session to report on. `null` clears the state.
+ * @param cwd - The session's working directory, included only so a
+ * change to it triggers a refetch; the server reads the stored value.
+ * @returns The status, a `loading` flag and a `refetch` for manual use.
+ */
+export function useWorkspaceStatus(
+ agentId: string | null,
+ sessionId: string | null,
+ cwd: string | null,
+) {
+ const [status, setStatus] = useState<WorkspaceStatus | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Bumped by every call, so only the newest one may write. Two git
+ // subprocesses per request means a slow workspace can answer after
+ // the user has already moved on, and nothing here polls — a stale
+ // branch would stay on screen until the next reply ends.
+ const reqId = useRef(0);
+
+ const refetch = useCallback(async () => {
+ const id = ++reqId.current;
+ if (!agentId || !sessionId) {
+ setStatus(null);
+ return;
+ }
+ setLoading(true);
+ try {
+ const next = await workspaceApi.status(agentId, sessionId);
+ if (id === reqId.current) setStatus(next);
+ } catch {
+ // A workspace that cannot be reached is reported the same way
+ // as one without a repository: no badge. `silent` on the call
+ // already suppressed the toast.
+ if (id === reqId.current) setStatus(null);
+ } finally {
+ // Guarded too: an overtaken request must not clear the
+ // spinner while its replacement is still in flight.
+ if (id === reqId.current) setLoading(false);
+ }
+ // `cwd` is not read here — it is a dependency so that moving the
+ // session re-runs this.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [agentId, sessionId, cwd]);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ return { status, loading, refetch };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index d852c07df..429ad1836 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -595,14 +595,16 @@
"emptyTitle": "No results",
"emptyDescription": "Nothing matches “{{query}}”."
},
- "loading": "Loading…"
- },
- "team-sidebar": {
- "membersHeading": "Members",
- "noMembers": "No members yet — ask the leader to spawn one with AgentCreate.",
- "running": "Running",
- "idle": "Idle",
- "missingSession": "(no session)"
+ "loading": "Loading…",
+ "team": {
+ "membersHeading": "Members",
+ "noMembers": "No members yet — ask the leader to spawn one with AgentCreate.",
+ "emptyTitle": "No team",
+ "emptyDescription": "This session is not part of a team. The agent forms one with TeamCreate.",
+ "running": "Running",
+ "idle": "Idle",
+ "missingSession": "(no session)"
+ }
},
"channel": {
"title": "Channels",
@@ -767,5 +769,16 @@
"agent-menu": {
"settings": "Settings",
"delete": "Delete agent"
+ },
+ "workdir": {
+ "title": "Working directory",
+ "description": "Pick the agent's working directory.",
+ "root": "Workspace root",
+ "parent": "Up one level",
+ "errorTitle": "Could not list this folder",
+ "pathPlaceholder": "Type or paste a path",
+ "empty": "This folder is empty",
+ "pressEnter": "Press Enter to check this path first",
+ "gitTooltip": "{{staged}} staged · {{unstaged}} modified · {{untracked}} untracked\nLine counts exclude untracked files"
}
}
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index caf24d002..260e8fde0 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -595,14 +595,16 @@
"emptyTitle": "无结果",
"emptyDescription": "没有匹配 “{{query}}” 的结果。"
},
- "loading": "加载中…"
- },
- "team-sidebar": {
- "membersHeading": "成员",
- "noMembers": "还没有成员——让队长用 AgentCreate 添加一个。",
- "running": "运行中",
- "idle": "空闲",
- "missingSession": "(无会话)"
+ "loading": "加载中…",
+ "team": {
+ "membersHeading": "成员",
+ "noMembers": "还没有成员——让队长用 AgentCreate 添加一个。",
+ "emptyTitle": "没有团队",
+ "emptyDescription": "当前会话不属于任何团队。agent 会用 TeamCreate 建立团队。",
+ "running": "运行中",
+ "idle": "空闲",
+ "missingSession": "(无会话)"
+ }
},
"channel": {
"title": "频道",
@@ -767,5 +769,16 @@
"agent-menu": {
"settings": "设置",
"delete": "删除智能体"
+ },
+ "workdir": {
+ "title": "工作目录",
+ "description": "选择智能体的工作目录。",
+ "root": "工作区根目录",
+ "parent": "上一级",
+ "errorTitle": "无法列出该文件夹",
+ "pathPlaceholder": "输入或粘贴路径",
+ "empty": "此文件夹为空",
+ "pressEnter": "先按回车校验该路径",
+ "gitTooltip": "{{staged}} 已暂存 · {{unstaged}} 已修改 · {{untracked}} 未跟踪\n行数不含未跟踪文件"
}
}
diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
index 175348230..813071497 100644
--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx
@@ -1,9 +1,23 @@
import type { PermissionContext } from '@agentscope-ai/agentscope/permission';
import type { TaskContext } from '@agentscope-ai/agentscope/state';
-import { BookText, ChevronDown, Database, ListTodo, PanelRight, ShieldCheck } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-
-import type { ChatModelConfig, SessionKnowledgeConfig, TTSModelConfig } from '@/api';
+import {
+ BookText,
+ ChevronDown,
+ Database,
+ ListTodo,
+ PanelRight,
+ ShieldCheck,
+ UsersRound,
+} from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import type {
+ ChatModelConfig,
+ PermissionMode,
+ SessionKnowledgeConfig,
+ TTSModelConfig,
+ UpdateSessionRequest,
+} from '@/api';
import { sessionApi } from '@/api';
import MCPSvg from '@/assets/images/mcp.svg?react';
import { ChatContent } from '@/components/chat/ChatContent.tsx';
@@ -15,6 +29,7 @@ import { PanelDock, type PanelDescriptor, type PanelKey } from '@/components/pan
import { PermissionPanel } from '@/components/panel/PermissionPanel';
import { SkillPanel } from '@/components/panel/SkillPanel';
import { TaskPanel } from '@/components/panel/TaskPanel';
+import { TeamPanel } from '@/components/panel/TeamPanel';
import { KnowledgeBaseParametersPopover } from '@/components/popover/KnowledgeBaseParametersPopover';
import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';
import { LlmSelect } from '@/components/select/LlmSelect';
@@ -39,6 +54,7 @@ import { useKnowledgeBases } from '@/hooks/useKnowledgeBases';
import { useMessages } from '@/hooks/useMessages';
import { useSessions } from '@/hooks/useSessions';
import { useWorkspace } from '@/hooks/useWorkspace.ts';
+import { useWorkspaceStatus } from '@/hooks/useWorkspaceStatus';
import { useTranslation } from '@/i18n/useI18n';
interface ChatViewportProps {
@@ -76,6 +92,7 @@ const KNOWN_PANELS: Record<PanelKey, true> = {
skill: true,
permission: true,
knowledge: true,
+ team: true,
};
/**
@@ -156,16 +173,6 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
const { sessions, refetch: refetchSessions } = useSessions(agentId);
const { groups } = useAvailableModels();
- // When the viewport agent differs from the outer page's selected
- // agent (i.e. user drilled into a team member), `refetchSessions`
- // only refreshes the member's session list. The team sidebar is
- // driven by the leader's session list owned by the outer page, so
- // we also fire the parent's refetch to keep that in sync.
- const handleTeamUpdated = useCallback(() => {
- refetchSessions();
- onTeamUpdated?.();
- }, [refetchSessions, onTeamUpdated]);
-
const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);
const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(
null,
@@ -178,6 +185,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);
const [tasksContext, setTasksContext] = useState<TaskContext | null>(null);
const [permissionContext, setPermissionContext] = useState<PermissionContext | null>(null);
+ const [configPending, setConfigPending] = useState(false);
// Dock layout: columns laid out left→right, each holding up to 2
// panels stacked top→bottom. Open order determines placement.
// Persisted so leaving and returning to /chat keeps the same panels.
@@ -187,6 +195,26 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
localStorage.setItem(PANEL_LAYOUT_KEY, JSON.stringify(panelLayout));
}, [panelLayout]);
+ // When the viewport agent differs from the outer page's selected
+ // agent (i.e. user drilled into a team member), `refetchSessions`
+ // only refreshes the member's session list, so we also fire the
+ // parent's refetch to keep its copy in sync.
+ //
+ // Surfacing the team panel here is what makes a team visible at all
+ // — `TeamCreate` / `AgentCreate` / `AgentInvite` are agent tools, so
+ // the user never opened a dialog that could have opened the panel.
+ // `team_updated` also fires on `TeamDelete` and carries no payload,
+ // hence checking the refetched list rather than opening blindly.
+ const handleTeamUpdated = useCallback(async () => {
+ const next = await refetchSessions();
+ if (next.some((v) => v.session.id === sessionId && v.team)) {
+ // `openPanelInLayout`, not `togglePanel` — the latter would
+ // close a panel the user already has open.
+ setPanelLayout((layout) => openPanelInLayout(layout, 'team'));
+ }
+ onTeamUpdated?.();
+ }, [refetchSessions, sessionId, onTeamUpdated]);
+
const handleStateUpdated = useCallback((value: Record<string, unknown>) => {
if (value.tasks_context) {
setTasksContext(value.tasks_context as TaskContext);
@@ -196,11 +224,19 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
}
}, []);
- const { msgs, phase, send, onUserConfirm, onSubagentConfirm, subagentHitl, interrupt } =
- useMessages(agentId, sessionId, {
- onTeamUpdated: handleTeamUpdated,
- onStateUpdated: handleStateUpdated,
- });
+ const {
+ msgs,
+ loading: messagesLoading,
+ phase,
+ send,
+ onUserConfirm,
+ onSubagentConfirm,
+ subagentHitl,
+ interrupt,
+ } = useMessages(agentId, sessionId, {
+ onTeamUpdated: handleTeamUpdated,
+ onStateUpdated: handleStateUpdated,
+ });
const {
mcps,
loading: mcpsLoading,
@@ -247,16 +283,71 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
*
* @param config - New attachment, or `null` to detach all.
*/
- const handleKnowledgeConfigChange = useCallback(
- async (config: SessionKnowledgeConfig | null) => {
+ /**
+ * Persist a session config change, applying it locally only once
+ * the server accepts it.
+ *
+ * The backend rejects config writes with 409 while a chat run holds
+ * the session, so an optimistic update would leave the control
+ * showing a value the session does not have. Waiting for the
+ * response keeps the control on its previous value with no rollback
+ * bookkeeping; `client.ts` has already surfaced the error toast by
+ * the time we land in `catch`.
+ *
+ * Declared above `panels` for the same temporal-dead-zone reason as
+ * `handleKnowledgeConfigChange` below.
+ *
+ * @param body - The PATCH body.
+ * @param apply - Mirrors the change into local state on success.
+ */
+ const patchConfig = useCallback(
+ async (body: UpdateSessionRequest, apply: () => void) => {
if (!sessionId || !agentId) return;
- setSelectedKnowledgeConfig(config);
- await sessionApi.update(sessionId, agentId, { knowledge_config: config });
- await refetchSessions();
+ setConfigPending(true);
+ try {
+ await sessionApi.update(sessionId, agentId, body);
+ apply();
+ await refetchSessions();
+ } catch {
+ // Toast already shown; local state deliberately untouched.
+ } finally {
+ setConfigPending(false);
+ }
},
[sessionId, agentId, refetchSessions],
);
+ const handleKnowledgeConfigChange = useCallback(
+ async (config: SessionKnowledgeConfig | null) => {
+ await patchConfig({ knowledge_config: config }, () =>
+ setSelectedKnowledgeConfig(config),
+ );
+ },
+ [patchConfig],
+ );
+
+ // Declared above `panels` — the memo factory reads `view.team`
+ // eagerly on first render, so a later `const` would still be in
+ // the temporal dead zone.
+ const view = sessions.find((v) => v.session.id === sessionId) ?? null;
+
+ const { status: workspaceStatus, refetch: refetchWorkspaceStatus } = useWorkspaceStatus(
+ agentId,
+ sessionId,
+ view?.session.config.cwd ?? null,
+ );
+
+ // A finished reply is the one moment the agent may have changed the
+ // working tree, and it is why nothing polls for git status. Watching
+ // `phase` rather than the REPLY_END event also covers the interrupt
+ // timeout, which reaches idle without one.
+ const prevPhaseRef = useRef(phase);
+ useEffect(() => {
+ const wasRunning = prevPhaseRef.current !== 'idle';
+ prevPhaseRef.current = phase;
+ if (wasRunning && phase === 'idle') void refetchWorkspaceStatus();
+ }, [phase, refetchWorkspaceStatus]);
+
// Build the panel descriptors with live data. Rebuilt on every
// data change so the dock always renders the latest state — the
// dock itself stays free of any data dependency.
@@ -337,6 +428,18 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
/>
),
},
+ team: {
+ title: (
+ <span className="flex items-center gap-x-2">
+ {t('common.team')}
+ {view?.team ? (
+ <Badge variant="outline">{view.team.members.length}</Badge>
+ ) : null}
+ </span>
+ ),
+ icon: <UsersRound className="size-4" />,
+ content: <TeamPanel team={view?.team ?? null} currentSessionId={sessionId} />,
+ },
}),
[
t,
@@ -358,11 +461,10 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
kbMiddlewareSchema,
handleKnowledgeConfigChange,
sessionId,
+ view,
],
);
- const view = sessions.find((v) => v.session.id === sessionId) ?? null;
-
// ChatViewport keeps its own `useSessions(agentId)` instance (the
// outer page has a separate one). Its built-in fetch only fires on
// `agentId` change, so when the outer page creates a new session
@@ -426,36 +528,30 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
};
};
- // Sync tasksContext from the session snapshot. Real-time updates
- // arrive via the CustomEvent(name="state_updated") → the
- // onStateUpdated callback above. We always mirror the snapshot
- // (including clearing to null when the session is gone or has no
- // tasks yet) so that switching sessions doesn't leak stale tasks
- // from the previous one.
+ // Seed tasks + permission from the session snapshot ONCE per
+ // session, then leave them to the CustomEvent(name="state_updated")
+ // stream via `handleStateUpdated`.
+ //
+ // Seeding on every `view` change would be wrong: storage is only
+ // written when a run ends, so mid-run the snapshot still holds the
+ // run-start values. `view` gets a new identity on every
+ // `refetchSessions()` — which `team_updated` triggers — and
+ // re-seeding then would silently roll both panels back to where the
+ // reply started. Clearing on `!view` still matters so switching
+ // sessions cannot leak the previous session's tasks or rules.
+ const seededSessionRef = useRef<string | null>(null);
useEffect(() => {
if (!view) {
+ seededSessionRef.current = null;
setTasksContext(null);
- return;
- }
- const tc = (view.session.state as Record<string, unknown>)?.tasks_context as
- | TaskContext
- | undefined;
- setTasksContext(tc ?? null);
- }, [view]);
-
- // Sync permissionContext from the session snapshot, mirroring the
- // tasksContext approach above. Real-time updates arrive via the
- // state_updated event → handleStateUpdated. Clearing to null when
- // the session is gone avoids leaking stale rules across sessions.
- useEffect(() => {
- if (!view) {
setPermissionContext(null);
return;
}
- const pc = (view.session.state as Record<string, unknown>)?.permission_context as
- | PermissionContext
- | undefined;
- setPermissionContext(pc ?? null);
+ if (seededSessionRef.current === view.session.id) return;
+ seededSessionRef.current = view.session.id;
+ const state = view.session.state as Record<string, unknown> | undefined;
+ setTasksContext((state?.tasks_context as TaskContext) ?? null);
+ setPermissionContext((state?.permission_context as PermissionContext) ?? null);
}, [view]);
// Sync selectedModel + selectedFallbackModel from the session
@@ -479,8 +575,16 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
if (firstModel) {
setSelectedModel(firstModel);
if (sessionId && agentId) {
+ // `silent` because the user did not ask for this write —
+ // surfacing a toast for a revoked credential or a network
+ // blip they never triggered is pure noise.
sessionApi
- .update(sessionId, agentId, { chat_model_config: firstModel })
+ .update(
+ sessionId,
+ agentId,
+ { chat_model_config: firstModel },
+ { silent: true },
+ )
.then(() => refetchSessions())
.catch(() => {});
}
@@ -512,10 +616,8 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
* because the primary selector does not allow clearing.
*/
const handleLlmChange = async (config: ChatModelConfig | null) => {
- if (!config || !sessionId || !agentId) return;
- setSelectedModel(config);
- await sessionApi.update(sessionId, agentId, { chat_model_config: config });
- await refetchSessions();
+ if (!config) return;
+ await patchConfig({ chat_model_config: config }, () => setSelectedModel(config));
};
/**
@@ -524,11 +626,9 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
* @param parameters - New parameter map (model-provider specific).
*/
const handleParametersChange = async (parameters: Record<string, unknown>) => {
- if (!selectedModel || !sessionId || !agentId) return;
+ if (!selectedModel) return;
const updated = { ...selectedModel, parameters };
- setSelectedModel(updated);
- await sessionApi.update(sessionId, agentId, { chat_model_config: updated });
- await refetchSessions();
+ await patchConfig({ chat_model_config: updated }, () => setSelectedModel(updated));
};
/**
@@ -537,10 +637,9 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
* @param config - New fallback config or `null` to clear.
*/
const handleFallbackChange = async (config: ChatModelConfig | null) => {
- if (!sessionId || !agentId) return;
- setSelectedFallbackModel(config);
- await sessionApi.update(sessionId, agentId, { fallback_chat_model_config: config });
- await refetchSessions();
+ await patchConfig({ fallback_chat_model_config: config }, () =>
+ setSelectedFallbackModel(config),
+ );
};
/**
@@ -549,10 +648,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
* @param config - New TTS config or `null` to disable.
*/
const handleTTSChange = async (config: TTSModelConfig | null) => {
- if (!sessionId || !agentId) return;
- setSelectedTTSModel(config);
- await sessionApi.update(sessionId, agentId, { tts_model_config: config });
- await refetchSessions();
+ await patchConfig({ tts_model_config: config }, () => setSelectedTTSModel(config));
};
/**
@@ -560,11 +656,33 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
*
* @param mode - New permission mode (e.g. `default`, `explore`).
*/
- const handlePermissionModeChange = async (mode: string) => {
- setSelectedPermissionMode(mode);
+ /**
+ * Persist a new working directory.
+ *
+ * Nothing local mirrors it — the value is read straight off the
+ * session view, which `patchConfig` refetches on success.
+ *
+ * @param next - Directory relative to the workspace root, or `null`
+ * for the root itself.
+ */
+ const handleCwdChange = async (next: string | null) => {
+ // Bypasses `patchConfig`: the dialog shows the failure inline and
+ // stays open on it, so the toast would be a duplicate and the
+ // swallowed rejection would let the dialog close as if it worked.
if (!sessionId || !agentId) return;
- await sessionApi.update(sessionId, agentId, { permission_mode: mode });
- await refetchSessions();
+ setConfigPending(true);
+ try {
+ await sessionApi.update(sessionId, agentId, { cwd: next }, { silent: true });
+ await refetchSessions();
+ } finally {
+ setConfigPending(false);
+ }
+ };
+
+ const handlePermissionModeChange = async (mode: string) => {
+ await patchConfig({ permission_mode: mode as PermissionMode }, () =>
+ setSelectedPermissionMode(mode),
+ );
};
return (
@@ -589,6 +707,7 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
onChange={handleLlmChange}
onAddCredential={() => setCredentialOpen(true)}
refetchTrigger={credentialRefetchTrigger}
+ disabled={configPending}
/>
<ModelParametersPopover
selectedModel={selectedModel}
@@ -598,13 +717,14 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
onFallbackChange={handleFallbackChange}
selectedTTSModel={selectedTTSModel}
onTTSChange={handleTTSChange}
+ disabled={configPending}
/>
<PermissionModeSelect
id="tour-permission-mode"
variant={'ghost'}
className="font-mono text-muted-foreground hover:text-foreground"
value={selectedPermissionMode}
- disabled={!sessionId}
+ disabled={!sessionId || configPending}
onChange={handlePermissionModeChange}
/>
<DropdownMenu>
@@ -659,6 +779,14 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
<Database />
{t('panel.knowledge.title')}
</DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem
+ checked={isPanelOpen('team')}
+ onCheckedChange={() => togglePanel('team')}
+ onSelect={(e) => e.preventDefault()}
+ >
+ <UsersRound />
+ {t('common.team')}
+ </DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -667,11 +795,25 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport
<ChatContent
className={'max-w-[var(--chat-content-w)] w-full'}
msgs={msgs}
+ loading={messagesLoading}
+ agentId={agentId}
+ sessionId={sessionId}
+ cwd={view?.session.config.cwd ?? null}
+ onCwdChange={handleCwdChange}
+ git={workspaceStatus?.git ?? null}
+ onRefreshGit={refetchWorkspaceStatus}
phase={phase}
disabled={selectedModel === null}
onSend={send}
onUserConfirm={onUserConfirm}
onInterrupt={interrupt}
+ // cwd={
+ // {cwd: view?.session.config.cwd, git: {
+ // branch: 'main',
+ // deletion: 0,
+ // addition: 0,
+ // }}
+ // }
footerSlot={
subagentHitl.length > 0 ? (
<SubagentHitlCard
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index 1451976c8..94f2c5028 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -21,7 +21,6 @@ import { DeleteDialog } from '@/components/dialog/DeleteDialog';
import { EditAgentDialog } from '@/components/dialog/EditAgentDialog';
import { RenameSessionDialog } from '@/components/dialog/RenameSessionDialog';
import { AgentSelect } from '@/components/select/AgentSelect';
-import { TeamSidebar } from '@/components/team/TeamSidebar';
import { ChatTourController } from '@/components/tour/ChatTourController';
import { Button } from '@/components/ui/button';
import {
@@ -215,7 +214,9 @@ const ChatPageInner = () => {
* container, which would otherwise cover the app rail.
*/}
<Sidebar collapsible={isMobile ? 'offcanvas' : 'none'} className="rounded-[22px]">
- <SidebarContent className="my-2">
+ {/* Scrolling moves down to the session list below, so the
+ agent picker and the new-session button stay put. */}
+ <SidebarContent className="my-2 overflow-hidden">
<SidebarGroup className="px-2 py-0">
<SidebarGroupLabel className="justify-between">
{t('common.agent')}
@@ -267,14 +268,14 @@ const ChatPageInner = () => {
</DropdownMenu>
</SidebarGroupContent>
</SidebarGroup>
- <SidebarGroup className="mt-5 px-2 py-0">
+ <SidebarGroup className="mt-5 min-h-0 flex-1 px-2 py-0">
<SidebarGroupLabel className="justify-between">
{t('chat.session.label')}
<span className="text-[10px] text-text-data font-mono">
{sessions.length}
</span>
</SidebarGroupLabel>
- <SidebarGroupContent>
+ <SidebarGroupContent className="flex min-h-0 flex-1 flex-col">
<SidebarGroup>
<SidebarMenu className="mb-2">
<Button id="tour-create-session" onClick={handleCreateSession}>
@@ -284,205 +285,208 @@ const ChatPageInner = () => {
</SidebarMenu>
</SidebarGroup>
- {sessions.length === 0 ? (
- <Empty className="border-none py-4 min-h-50">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <MessageSquareDashed />
- </EmptyMedia>
- <EmptyTitle>{t('chat.session.emptyTitle')}</EmptyTitle>
- <EmptyDescription>
- {urlAgentId
- ? t('chat.session.emptyHasAgent')
- : t('chat.session.emptyNoAgent')}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- <>
- <SidebarGroup>
- <SidebarGroupLabel>
- {t('chat.session.today')}
- </SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>
- {todaySessions.map((view) => {
- const session = view.session;
- const SourceIcon =
- SOURCE_ICON[session.source] ??
- BotMessageSquare;
- return (
- <SidebarMenuItem key={session.id}>
- {/* Wider right gutter than the stock
+ <div className="no-scrollbar min-h-0 flex-1 overflow-y-auto">
+ {sessions.length === 0 ? (
+ <Empty className="border-none py-4 min-h-50">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <MessageSquareDashed />
+ </EmptyMedia>
+ <EmptyTitle>{t('chat.session.emptyTitle')}</EmptyTitle>
+ <EmptyDescription>
+ {urlAgentId
+ ? t('chat.session.emptyHasAgent')
+ : t('chat.session.emptyNoAgent')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <>
+ <SidebarGroup>
+ <SidebarGroupLabel>
+ {t('chat.session.today')}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {todaySessions.map((view) => {
+ const session = view.session;
+ const SourceIcon =
+ SOURCE_ICON[session.source] ??
+ BotMessageSquare;
+ return (
+ <SidebarMenuItem key={session.id}>
+ {/* Wider right gutter than the stock
pr-8: the badge holds a mono timestamp. */}
- <SidebarMenuButton
- className="text-muted-foreground hover:text-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-16"
- isActive={
- urlSessionId === session.id
- }
- onClick={() => {
- navigate(
- `/chat/${urlAgentId}/${session.id}`,
- );
- setOpenMobile(false);
- }}
- >
- {showSourceIcons && <SourceIcon />}
- <span className="truncate">
- {session.config.name ||
- session.id}
- </span>
- </SidebarMenuButton>
- {/* Badge and action are mutually exclusive.
+ <SidebarMenuButton
+ className="text-muted-foreground hover:text-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-16"
+ isActive={
+ urlSessionId === session.id
+ }
+ onClick={() => {
+ navigate(
+ `/chat/${urlAgentId}/${session.id}`,
+ );
+ setOpenMobile(false);
+ }}
+ >
+ {showSourceIcons && (
+ <SourceIcon />
+ )}
+ <span className="truncate">
+ {session.config.name ||
+ session.id}
+ </span>
+ </SidebarMenuButton>
+ {/* Badge and action are mutually exclusive.
Keyboard focus reveals the action, plain
focus-within does not — otherwise clicking
the row would pin it open. */}
- <SidebarMenuBadge className="max-md:hidden group-hover/menu-item:hidden group-has-focus-visible/menu-item:hidden group-has-data-[state=open]/menu-item:hidden text-text-tertiary! font-mono">
- {format(
- new Date(
- view.session.created_at,
- ),
- 'HH:mm',
- )}
- </SidebarMenuBadge>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <SidebarMenuAction className="md:opacity-0 group-hover/menu-item:opacity-100 group-has-focus-visible/menu-item:opacity-100 aria-expanded:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground">
- <Ellipsis />
- </SidebarMenuAction>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="w-auto"
- side="right"
- align="start"
- >
- <DropdownMenuItem
- onClick={() => {
- setRenameSession(
- session,
- );
- setRenameOpen(true);
- }}
+ <SidebarMenuBadge className="max-md:hidden group-hover/menu-item:hidden group-has-focus-visible/menu-item:hidden group-has-data-[state=open]/menu-item:hidden text-text-tertiary! font-mono">
+ {format(
+ new Date(
+ view.session.created_at,
+ ),
+ 'HH:mm',
+ )}
+ </SidebarMenuBadge>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SidebarMenuAction className="md:opacity-0 group-hover/menu-item:opacity-100 group-has-focus-visible/menu-item:opacity-100 aria-expanded:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground">
+ <Ellipsis />
+ </SidebarMenuAction>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ className="w-auto"
+ side="right"
+ align="start"
>
- <Pencil />
- {t('session-menu.rename')}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onClick={() =>
- requestDeleteSession(
- session,
- )
- }
- >
- <Trash2 />
- {t('session-menu.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- <SidebarGroup>
- <SidebarGroupLabel>
- {t('chat.session.earlier')}
- </SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>
- {earlierSessions.map((view) => {
- const session = view.session;
- const SourceIcon =
- SOURCE_ICON[session.source] ??
- BotMessageSquare;
- return (
- <SidebarMenuItem key={session.id}>
- <SidebarMenuButton
- className="text-muted-foreground hover:text-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-16"
- isActive={
- urlSessionId === session.id
- }
- onClick={() => {
- navigate(
- `/chat/${urlAgentId}/${session.id}`,
- );
- setOpenMobile(false);
- }}
- >
- {showSourceIcons && <SourceIcon />}
- <span className="truncate">
- {session.config.name ||
- session.id}
- </span>
- </SidebarMenuButton>
- <SidebarMenuBadge className="max-md:hidden group-hover/menu-item:hidden group-has-focus-visible/menu-item:hidden group-has-data-[state=open]/menu-item:hidden text-text-tertiary! font-mono">
- {format(
- new Date(
- view.session.created_at,
- ),
- 'MMM dd',
- )}
- </SidebarMenuBadge>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <SidebarMenuAction className="md:opacity-0 group-hover/menu-item:opacity-100 group-has-focus-visible/menu-item:opacity-100 aria-expanded:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground">
- <Ellipsis />
- </SidebarMenuAction>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="w-auto"
- side="right"
- align="start"
+ <DropdownMenuItem
+ onClick={() => {
+ setRenameSession(
+ session,
+ );
+ setRenameOpen(true);
+ }}
+ >
+ <Pencil />
+ {t(
+ 'session-menu.rename',
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ requestDeleteSession(
+ session,
+ )
+ }
+ >
+ <Trash2 />
+ {t(
+ 'session-menu.delete',
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuItem>
+ );
+ })}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ <SidebarGroup>
+ <SidebarGroupLabel>
+ {t('chat.session.earlier')}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {earlierSessions.map((view) => {
+ const session = view.session;
+ const SourceIcon =
+ SOURCE_ICON[session.source] ??
+ BotMessageSquare;
+ return (
+ <SidebarMenuItem key={session.id}>
+ <SidebarMenuButton
+ className="text-muted-foreground hover:text-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-16"
+ isActive={
+ urlSessionId === session.id
+ }
+ onClick={() => {
+ navigate(
+ `/chat/${urlAgentId}/${session.id}`,
+ );
+ setOpenMobile(false);
+ }}
>
- <DropdownMenuItem
- onClick={() => {
- setRenameSession(
- session,
- );
- setRenameOpen(true);
- }}
- >
- <Pencil />
- {t('session-menu.rename')}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onClick={() =>
- requestDeleteSession(
- session,
- )
- }
+ {showSourceIcons && (
+ <SourceIcon />
+ )}
+ <span className="truncate">
+ {session.config.name ||
+ session.id}
+ </span>
+ </SidebarMenuButton>
+ <SidebarMenuBadge className="max-md:hidden group-hover/menu-item:hidden group-has-focus-visible/menu-item:hidden group-has-data-[state=open]/menu-item:hidden text-text-tertiary! font-mono">
+ {format(
+ new Date(
+ view.session.created_at,
+ ),
+ 'MMM dd',
+ )}
+ </SidebarMenuBadge>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SidebarMenuAction className="md:opacity-0 group-hover/menu-item:opacity-100 group-has-focus-visible/menu-item:opacity-100 aria-expanded:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground">
+ <Ellipsis />
+ </SidebarMenuAction>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ className="w-auto"
+ side="right"
+ align="start"
>
- <Trash2 />
- {t('session-menu.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- </>
- )}
+ <DropdownMenuItem
+ onClick={() => {
+ setRenameSession(
+ session,
+ );
+ setRenameOpen(true);
+ }}
+ >
+ <Pencil />
+ {t(
+ 'session-menu.rename',
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() =>
+ requestDeleteSession(
+ session,
+ )
+ }
+ >
+ <Trash2 />
+ {t(
+ 'session-menu.delete',
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuItem>
+ );
+ })}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ </>
+ )}
+ </div>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
</Sidebar>
- {/*
- * Team sidebar lives at the outer page level (not inside
- * ChatViewport) so navigating between leader and member
- * sessions does NOT unmount it. The team data comes from
- * the leader's session view, which is stable across that
- * navigation; only `currentSessionId` changes to drive
- * row highlighting.
- */}
- {currentView?.team && effectiveSessionId && (
- <TeamSidebar team={currentView.team} currentSessionId={effectiveSessionId} />
- )}
<div className="flex flex-1 min-w-0">
<ChatViewport
agentId={effectiveAgentId}
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index 107ea8665..922d41bb8 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -21,6 +21,7 @@ from ._service import (
KnowledgeBaseService,
ResourceAccessService,
SessionService,
+ WorkspaceService,
)
if TYPE_CHECKING:
@@ -157,6 +158,12 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
message_bus=message_bus,
)
+ app.state.workspace_service = WorkspaceService(
+ storage=storage,
+ workspace_manager=workspace_manager,
+ download_secret=app.state.download_secret,
+ )
+
# ---------------- Knowledge-base wiring ----------------
knowledge_base_service = None
if knowledge_base_manager is not None:
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index e21b0bc71..a8c8e2b6b 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -21,6 +21,7 @@ from ._workspace import (
AddSkillRequest,
AddSkillsFromLibraryRequest,
DirectoryEntry,
+ DirectoryListing,
DownloadTokenResponse,
MCPClientStatus,
ToolInfo,
@@ -99,6 +100,7 @@ __all__ = [
"AddSkillRequest",
"AddSkillsFromLibraryRequest",
"DirectoryEntry",
+ "DirectoryListing",
"DownloadTokenResponse",
"MCPClientStatus",
"ToolInfo",
diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.py
index caaa9baa4..ca393b6e3 100644
--- a/src/agentscope/app/_router/_schema/_session.py
+++ b/src/agentscope/app/_router/_schema/_session.py
@@ -139,6 +139,14 @@ class UpdateSessionRequest(BaseModel):
default=None,
description="New permission mode for the session.",
)
+ cwd: str | None = Field(
+ default=None,
+ description=(
+ "New working directory — absolute, or relative to the "
+ "workspace root, and not confined to it. Pass null to "
+ "reset to the root; omit to leave unchanged."
+ ),
+ )
class SessionView(BaseModel):
@@ -159,13 +167,32 @@ class SessionView(BaseModel):
session: SessionRecord = Field(
description=(
- "The persisted session record. Includes ``state`` "
- "(``permission_context`` / ``tool_context`` / "
- "``tasks_context``) inline."
+ "The persisted session record, with the bulk of ``state`` "
+ "stripped: ``context`` and ``summary`` are cleared and "
+ "``tool_context`` is reset. Those hold the conversation the "
+ "model sees and the contents of every file it has read, so "
+ "listing twenty sessions would otherwise ship twenty "
+ "transcripts to render a sidebar. ``permission_context`` "
+ "and ``tasks_context`` survive — they are small, and the UI "
+ "seeds its panels from them. Read a session's messages via "
+ "``GET /sessions/{id}/messages``."
),
)
is_running: bool = Field(
- description="Whether a chat run is currently active on this session.",
+ description=(
+ "**Deprecated** — use :attr:`status`. True only while a "
+ "worker holds the run lease, which a session parked on a "
+ "confirmation prompt does not: this reads ``False`` for a "
+ "session that is visibly waiting on the user."
+ ),
+ )
+ status: SessionStatus = Field(
+ description=(
+ "The session's unified status: ``running``, ``idle``, "
+ "``awaiting_permission`` or ``awaiting_external_result``. "
+ "Exactly one applies at any moment, so a single indicator "
+ "renders it without reconciling flags."
+ ),
)
team: TeamDetailResponse | None = Field(
default=None,
diff --git a/src/agentscope/app/_router/_schema/_workspace.py b/src/agentscope/app/_router/_schema/_workspace.py
index 65ca5ced9..455e78f6b 100644
--- a/src/agentscope/app/_router/_schema/_workspace.py
+++ b/src/agentscope/app/_router/_schema/_workspace.py
@@ -70,6 +70,23 @@ class DirectoryEntry(BaseModel):
)
+class DirectoryListing(BaseModel):
+ """One directory level, plus the path it actually resolved to."""
+
+ path: str = Field(
+ description=(
+ "Absolute path of the directory that was listed. Echoing "
+ "it back is what lets a caller that passed a relative path "
+ "(or none at all) show the user where they really are — "
+ "the workspace root is backend-dependent and otherwise "
+ "unknowable client-side."
+ ),
+ )
+ entries: list[DirectoryEntry] = Field(
+ description="The directory's immediate children, unsorted.",
+ )
+
+
class DownloadTokenResponse(BaseModel):
"""A capability authorizing one download of one path."""
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index 4524fb549..c2e222ec7 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -36,6 +36,7 @@ from .._service import (
ResourceAccessService,
ChatService,
SessionService,
+ SessionStatus,
SessionProjection,
SubagentHitlProjector,
)
@@ -49,6 +50,7 @@ from ..storage import (
TeamRecord,
)
from ...message import ToolCallState
+from ...state import ToolContext
from ..storage._utils import _ensure_team_members
from ...event import CustomEvent
from ..workspace_manager import WorkspaceManagerBase
@@ -199,12 +201,16 @@ async def list_sessions(
"""Return all sessions for an agent as enriched
:class:`SessionView` entries.
- Each entry bundles three things the chat UI needs to render
- without follow-up requests: the session record (incl.
- ``state``), whether a chat run is currently active, and — when
+ Each entry bundles what the chat UI needs to render without
+ follow-up requests: the session record, its status, and — when
the session participates in a team — the resolved team detail
(leader agent + member agents with their session ids).
+ The record arrives trimmed: ``state.context``, ``state.summary``
+ and ``state.tool_context`` are cleared, since they hold the model's
+ conversation and every file it has read. Fetch a session's messages
+ from ``GET /sessions/{id}/messages`` instead.
+
Args:
agent_id (`str`):
Agent whose sessions to list. May be an agent shared to
@@ -244,12 +250,34 @@ async def list_sessions(
user_id,
team_record,
)
+ is_running = await message_bus.is_locked(
+ MessageBusKeys.session_lock(session.id),
+ )
+ # Derived before the trim below, which drops the context it reads.
+ session_status = (
+ SessionStatus.RUNNING
+ if is_running
+ else SessionService.derive_parked_status(session.state.context)
+ )
views.append(
SessionView(
- session=session,
- is_running=await message_bus.is_locked(
- MessageBusKeys.session_lock(session.id),
+ # ``context`` is the conversation the model sees,
+ # ``summary`` its compressed form, and ``tool_context``
+ # caches every file read — megabytes a session, none of
+ # which a sidebar renders.
+ session=session.model_copy(
+ update={
+ "state": session.state.model_copy(
+ update={
+ "context": [],
+ "summary": "",
+ "tool_context": ToolContext(),
+ },
+ ),
+ },
),
+ is_running=is_running,
+ status=session_status,
team=team_detail,
),
)
@@ -431,8 +459,14 @@ async def update_session(
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
access: ResourceAccessService = Depends(get_resource_access_service),
+ message_bus: MessageBus = Depends(get_message_bus),
) -> SessionRecord:
- """Update the model configuration of an existing session.
+ """Update the configuration of an existing session.
+
+ Rejected while a chat run holds the session: the agent snapshots
+ its configuration once at run start, so a mid-run change would be
+ ignored for the current reply anyway — and writing it would race
+ the run's own state persistence.
Args:
session_id (`str`): The session to update.
@@ -440,13 +474,16 @@ async def update_session(
user_id (`str`): Injected authenticated user ID.
storage (`StorageBase`): Injected storage backend.
access (`ResourceAccessService`): Injected access service.
+ message_bus (`MessageBus`): Injected message bus; used to
+ detect an in-flight run.
Returns:
`SessionRecord`: The full session record after the update.
Raises:
`HTTPException`: 404 if the session does not exist, or if the
- referenced credential / KB is not visible to the caller.
+ referenced credential / KB is not visible to the caller;
+ 409 if a chat run is currently active on the session.
"""
existing = await storage.get_session(user_id, agent_id, session_id)
if existing is None:
@@ -455,6 +492,17 @@ async def update_session(
detail=f"Session '{session_id}' not found.",
)
+ # Checked after the 404 so a missing session reports as missing, and
+ # before the validation round trips below so we fail fast.
+ if await message_bus.is_locked(MessageBusKeys.session_lock(session_id)):
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=(
+ "Cannot modify session configuration while the session "
+ "is running."
+ ),
+ )
+
await _ensure_credential_exists(access, user_id, body.chat_model_config)
await _ensure_credential_exists(
access,
@@ -468,7 +516,13 @@ async def update_session(
body.knowledge_config,
)
- updated_state = existing.state
+ # ``None`` leaves the stored state untouched (see
+ # ``StorageBase.upsert_session``). ``permission_mode`` is the only
+ # request field living inside ``state``; every other field is a
+ # pure config write, and rewriting ``state`` for those would put
+ # this handler's opening snapshot back over whatever the run has
+ # persisted since.
+ updated_state = None
if body.permission_mode is not None:
updated_ctx = existing.state.permission_context.model_copy(
update={"mode": body.permission_mode},
diff --git a/src/agentscope/app/_router/_workspace.py b/src/agentscope/app/_router/_workspace.py
index 7946f2061..918535cef 100644
--- a/src/agentscope/app/_router/_workspace.py
+++ b/src/agentscope/app/_router/_workspace.py
@@ -19,34 +19,23 @@ from pydantic import ValidationError
from ..deps import (
get_current_user_id,
- get_download_secret,
get_skill_hubs,
get_storage,
- get_workspace_manager,
+ get_workspace_service,
)
from ..hub import SkillHubBase
-from .._service._download_token import (
- sign_download_token,
- verify_download_token,
-)
-from .._service._skill_upload import (
- SkillUploadError,
- UploadManifest,
- _install_slots,
- _tar_stream,
- _validate_manifest,
-)
-from ..workspace_manager import WorkspaceManagerBase
+from .._service import WorkspaceService, WorkspaceStatus
+from .._service._workspace import SkillUploadError, UploadManifest
from ..storage import MCPRecord, StorageBase
from ...mcp import MCPClient
from ...skill import Skill
-from ...workspace import WorkspaceBase
from ._schema import (
AddFromLibraryRequest,
AddFromLibraryResponse,
AddSkillRequest,
AddSkillsFromLibraryRequest,
DirectoryEntry,
+ DirectoryListing,
DownloadTokenResponse,
MCPClientStatus,
ToolInfo,
@@ -56,49 +45,6 @@ from ..._utils._common import _describe_exception
workspace_router = APIRouter(prefix="/workspace", tags=["workspace"])
-async def _resolve_workspace(
- user_id: str,
- agent_id: str,
- session_id: str,
- storage: StorageBase,
- workspace_manager: WorkspaceManagerBase,
-) -> WorkspaceBase:
- """Return the workspace backing the given session.
-
- Args:
- user_id (`str`):
- The authenticated user ID.
- agent_id (`str`):
- The agent owning the session.
- session_id (`str`):
- The session whose workspace is wanted.
- storage (`StorageBase`):
- The storage used to look the session record up.
- workspace_manager (`WorkspaceManagerBase`):
- The manager that opens or reattaches the workspace.
-
- Returns:
- `WorkspaceBase`:
- The session's workspace.
-
- Raises:
- `HTTPException`:
- ``404`` when the session does not exist.
- """
- session_record = await storage.get_session(user_id, agent_id, session_id)
- if session_record is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Session {session_id!r} not found.",
- )
- return await workspace_manager.get_workspace(
- user_id,
- agent_id,
- session_id,
- session_record.config.workspace_id,
- )
-
-
# ---------------------------------------------------------------------------
# MCP endpoints
# ---------------------------------------------------------------------------
@@ -109,16 +55,13 @@ async def list_mcps(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> list[MCPClientStatus]:
"""Return all MCP clients with live tool list and health status."""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
clients = await workspace.list_mcps()
@@ -157,7 +100,7 @@ async def add_mcp(
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> None:
"""Add an MCP client to the session's workspace.
@@ -167,12 +110,10 @@ async def add_mcp(
that MCP is defined, and adding it to a second workspace must not
silently redefine it.
"""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
await workspace.add_mcp(mcp)
@@ -195,7 +136,7 @@ async def add_mcps_from_library(
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> AddFromLibraryResponse:
"""Put MCPs the user has already installed into this workspace.
@@ -205,12 +146,10 @@ async def add_mcps_from_library(
Adding is per-MCP: one that fails to connect does not cancel the
rest, and the response says which ones landed.
"""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
present = {client.name for client in await workspace.list_mcps()}
@@ -243,16 +182,13 @@ async def remove_mcp(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> None:
"""Remove an MCP client from the session's workspace by name."""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
await workspace.remove_mcp(mcp_name)
@@ -267,16 +203,13 @@ async def list_skills(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> list[Skill]:
"""Return all skills available in the session's workspace."""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
return await workspace.list_skills()
@@ -291,8 +224,7 @@ async def add_skill(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> None:
"""Add a skill to the session's workspace from the given path.
@@ -301,12 +233,10 @@ async def add_skill(
to send a folder, or ``POST /skill/from-library`` to install one
the user already has.
"""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
await workspace.add_skill(body.skill_path)
@@ -326,8 +256,7 @@ async def upload_skill(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> None:
"""Install a skill from an uploaded folder.
@@ -338,41 +267,32 @@ async def upload_skill(
"""
try:
parsed = UploadManifest.model_validate_json(manifest)
- _validate_manifest(parsed)
+ workspace_service.validate_manifest(parsed, len(files))
except (ValidationError, SkillUploadError) as e:
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY,
str(e),
) from e
- if len(files) != len(parsed.entries):
- raise HTTPException(
- status.HTTP_422_UNPROCESSABLE_ENTITY,
- f"The manifest lists {len(parsed.entries)} files but "
- f"{len(files)} were sent.",
- )
-
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
- async with _install_slots:
- try:
- # dir_name is unused: the tar members already carry the
- # picked folder as their first path segment.
- await workspace.add_skill_archive(
- _tar_stream(parsed, files),
- "tar",
- "skill",
- )
- except (SkillUploadError, ValueError) as e:
- raise HTTPException(
- status.HTTP_422_UNPROCESSABLE_ENTITY,
- str(e),
- ) from e
+ try:
+ # The name is unused: the tar members already carry the picked
+ # folder as their first path segment.
+ await workspace_service.install_skill(
+ workspace,
+ workspace_service.tar_stream(parsed, files),
+ "tar",
+ "skill",
+ )
+ except (SkillUploadError, ValueError) as e:
+ raise HTTPException(
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
+ str(e),
+ ) from e
@workspace_router.post(
@@ -385,7 +305,7 @@ async def add_skills_from_library(
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
skill_hubs: dict[str, SkillHubBase] = Depends(get_skill_hubs),
) -> AddFromLibraryResponse:
"""Put skills the user has already installed into this workspace.
@@ -394,12 +314,10 @@ async def add_skills_from_library(
workspace; the server holds no copy in between. Adding is
per-skill, and the response says which ones landed.
"""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
added: list[str] = []
@@ -416,17 +334,17 @@ async def add_skills_from_library(
] = f"Its hub {record.hub_id!r} is no longer registered."
continue
try:
- async with _install_slots:
- archive = await hub.download(
- user_id,
- record.card_id or record.name,
- record.version,
- )
- await workspace.add_skill_archive(
- archive.stream,
- archive.format,
- record.name,
- )
+ archive = await hub.download(
+ user_id,
+ record.card_id or record.name,
+ record.version,
+ )
+ await workspace_service.install_skill(
+ workspace,
+ archive.stream,
+ archive.format,
+ record.name,
+ )
except Exception as e: # pylint: disable=broad-except
failed[record.name] = _describe_exception(e)
continue
@@ -444,16 +362,13 @@ async def remove_skill(
agent_id: str = Query(...),
session_id: str = Query(...),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> None:
"""Remove a skill from the session's workspace by name."""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
await workspace.remove_skill(skill_name)
@@ -475,21 +390,21 @@ async def list_workspace_directory(
),
),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
-) -> list[DirectoryEntry]:
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
+) -> DirectoryListing:
"""List one directory level, reachable from a session's workspace.
Paths are not confined to the workspace root: for a sandboxed
backend the reachable filesystem is the sandbox, and for a local
one the caller is already trusted with the host.
+
+ The resolved absolute path comes back alongside the entries, so a
+ caller browsing with relative paths can still show where it is.
"""
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
backend = workspace.get_backend()
target = backend.abspath(path, cwd=workspace.workdir)
@@ -508,15 +423,44 @@ async def list_workspace_directory(
# One call for the whole directory: asking per entry would be one
# round trip each on a sandboxed backend, times three attributes.
- return [
- DirectoryEntry(
- name=entry.name,
- is_dir=entry.is_dir,
- size_bytes=entry.size_bytes,
- updated_at=entry.mtime,
- )
- for entry in await backend.scandir(target)
- ]
+ return DirectoryListing(
+ path=target,
+ entries=[
+ DirectoryEntry(
+ name=entry.name,
+ is_dir=entry.is_dir,
+ size_bytes=entry.size_bytes,
+ updated_at=entry.mtime,
+ )
+ for entry in await backend.scandir(target)
+ ],
+ )
+
+
+@workspace_router.get("/status")
+async def get_workspace_status(
+ agent_id: str = Query(...),
+ session_id: str = Query(...),
+ user_id: str = Depends(get_current_user_id),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
+) -> WorkspaceStatus:
+ """Report where a session is pointed, and the git state of that place.
+
+ The directory comes from the session's own ``cwd`` rather than a
+ query parameter: it is the session's anchor, and resolving a
+ relative one needs the workspace root the client cannot see.
+
+ Git is best-effort. A directory that is not a repository is the
+ normal case, not an error, and the sandboxed backends differ in how
+ they report a missing binary or an unreachable container — so every
+ failure collapses to ``git: null`` and the rest of the response is
+ still served.
+ """
+ return await workspace_service.read_status(
+ user_id,
+ agent_id,
+ session_id,
+ )
@workspace_router.post("/files/download-token")
@@ -525,9 +469,7 @@ async def create_download_token(
session_id: str = Query(...),
path: str = Query(..., description="The path the token will authorize."),
user_id: str = Depends(get_current_user_id),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
- secret: str = Depends(get_download_secret),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> DownloadTokenResponse:
"""Mint a short-lived token for a browser-native download.
@@ -543,17 +485,18 @@ async def create_download_token(
browser navigation, so an error there surfaces as a raw error page
rather than something the UI can show.
"""
- await _resolve_workspace(
+ await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
# Signed verbatim, not resolved: the download verifies against the
# query string it receives, and resolving needs a user the token
# has not been read yet to supply.
- token, expires_at = sign_download_token(secret, user_id, path)
+ token, expires_at = workspace_service.sign_download_token(
+ user_id,
+ path,
+ )
return DownloadTokenResponse(token=token, expires_at=expires_at)
@@ -579,9 +522,7 @@ async def read_workspace_file(
),
),
x_user_id: str | None = Header(default=None),
- storage: StorageBase = Depends(get_storage),
- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),
- secret: str = Depends(get_download_secret),
+ workspace_service: WorkspaceService = Depends(get_workspace_service),
) -> StreamingResponse:
"""Stream one file out of a session's workspace.
@@ -591,7 +532,7 @@ async def read_workspace_file(
"""
if token is not None:
try:
- user_id = verify_download_token(secret, token, path)
+ user_id = workspace_service.verify_download_token(token, path)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -605,12 +546,10 @@ async def read_workspace_file(
detail="X-User-ID header or download token is required.",
)
- workspace = await _resolve_workspace(
+ workspace = await workspace_service.resolve(
user_id,
agent_id,
session_id,
- storage,
- workspace_manager,
)
backend = workspace.get_backend()
target = backend.abspath(path, cwd=workspace.workdir)
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 99a3176a3..1cfb55a88 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -20,12 +20,14 @@ from ._session import SessionService, SessionStatus
from ._session_projection import SessionProjection
from ._projectors import SubagentHitlProjector
from ._toolkit import get_toolkit
+from ._workspace import GitStatus, WorkspaceService, WorkspaceStatus
__all__ = [
"AgentView",
"ChannelService",
"ChatService",
"CredentialView",
+ "GitStatus",
"IndexSweeper",
"IndexTaskConsumer",
"IndexWorker",
@@ -37,6 +39,8 @@ __all__ = [
"SessionStatus",
"SessionProjection",
"SubagentHitlProjector",
+ "WorkspaceService",
+ "WorkspaceStatus",
"get_embedding_model",
"get_model",
"get_tts_model",
diff --git a/src/agentscope/app/_service/_download_token.py b/src/agentscope/app/_service/_download_token.py
deleted file mode 100644
index 875fceac7..000000000
--- a/src/agentscope/app/_service/_download_token.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Short-lived capability tokens for browser-native file downloads.
-
-A browser only streams a response to disk when it issues the request
-itself — a navigation or ``<a download>`` — and such a request cannot
-carry a custom header. Fetching with ``X-User-ID`` and building a blob
-works, but buffers the whole file in the tab.
-
-So the credential has to travel in the URL. A token minted here says
-"this exact user was already authenticated, and may read this exact
-path for the next minute" — a capability, not an identity. Only
-``GET /workspace/files`` accepts one, and minting depends on the normal
-identity dependency, so swapping in OAuth/JWT later changes where the
-capability comes from without touching how it is checked.
-"""
-import base64
-import hashlib
-import hmac
-import time
-
-# Long enough to survive a slow round trip and the user's click, short
-# enough that a token leaked through an access log or browser history
-# is already dead. There is no revocation list to fall back on.
-DEFAULT_DOWNLOAD_TOKEN_TTL = 60
-
-
-def _b64(raw: bytes) -> str:
- """Encode without padding, which is not URL-safe to round-trip."""
- return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
-
-
-def _unb64(text: str) -> bytes:
- """Reverse :func:`_b64`, restoring the stripped padding."""
- return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
-
-
-def _signature(secret: str, expires_at: int, user_id: str, path: str) -> bytes:
- """Compute the MAC binding an expiry, a user and a path together.
-
- ``\\0`` separates the fields because it cannot occur in any of them,
- so no combination of values can be re-cut into a different triple.
-
- Args:
- secret (`str`):
- The app-wide signing secret.
- expires_at (`int`):
- Unix timestamp after which the token is refused.
- user_id (`str`):
- The user the capability was granted to.
- path (`str`):
- The one path the capability covers.
-
- Returns:
- `bytes`:
- The raw HMAC-SHA256 digest.
- """
- message = f"{expires_at}\0{user_id}\0{path}".encode("utf-8")
- return hmac.new(secret.encode("utf-8"), message, hashlib.sha256).digest()
-
-
-def sign_download_token(
- secret: str,
- user_id: str,
- path: str,
- ttl: int = DEFAULT_DOWNLOAD_TOKEN_TTL,
-) -> tuple[str, int]:
- """Mint a token authorizing one download.
-
- Args:
- secret (`str`):
- The app-wide signing secret.
- user_id (`str`):
- The already-authenticated caller.
- path (`str`):
- The path the token authorizes, verbatim as the download
- request will send it.
- ttl (`int`, defaults to 60):
- Seconds the token stays valid.
-
- Returns:
- `tuple[str, int]`:
- The token and its expiry as a Unix timestamp.
- """
- expires_at = int(time.time()) + ttl
- signature = _signature(secret, expires_at, user_id, path)
- token = f"{expires_at}.{_b64(user_id.encode('utf-8'))}.{_b64(signature)}"
- return token, expires_at
-
-
-def verify_download_token(secret: str, token: str, path: str) -> str:
- """Return the user a token was granted to, for this path.
-
- The path is not read out of the token but re-derived from the
- request, so a token for one file cannot be replayed against
- another.
-
- Args:
- secret (`str`):
- The app-wide signing secret.
- token (`str`):
- The token from the request.
- path (`str`):
- The path the request is asking for.
-
- Returns:
- `str`:
- The user ID the token was minted for.
-
- Raises:
- `ValueError`:
- The token is malformed, expired, or does not match.
- """
- try:
- raw_expiry, raw_user, raw_signature = token.split(".")
- expires_at = int(raw_expiry)
- user_id = _unb64(raw_user).decode("utf-8")
- signature = _unb64(raw_signature)
- except (ValueError, UnicodeDecodeError) as e:
- raise ValueError("Malformed download token.") from e
-
- expected = _signature(secret, expires_at, user_id, path)
- if not hmac.compare_digest(signature, expected):
- raise ValueError("Invalid download token.")
- if expires_at < time.time():
- raise ValueError("Expired download token.")
- return user_id
diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.py
index 3a67d7e85..bea352608 100644
--- a/src/agentscope/app/_service/_session.py
+++ b/src/agentscope/app/_service/_session.py
@@ -199,10 +199,10 @@ class SessionService:
if session is None:
return None
- return self._derive_parked_status(session.state.context)
+ return self.derive_parked_status(session.state.context)
@staticmethod
- def _derive_parked_status(context: list) -> SessionStatus:
+ def derive_parked_status(context: list) -> SessionStatus:
"""Derive the parked :class:`SessionStatus` from a persisted
``AgentState.context``.
diff --git a/src/agentscope/app/_service/_skill_upload.py b/src/agentscope/app/_service/_skill_upload.py
deleted file mode 100644
index 64e3a8f71..000000000
--- a/src/agentscope/app/_service/_skill_upload.py
+++ /dev/null
@@ -1,161 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Turn a browser folder upload into a tar stream for a workspace.
-
-The browser sends one part per file plus a manifest of paths and sizes.
-The manifest is what makes streaming possible at all: a tar header must
-carry the member size *before* its bytes, and multipart parts do not
-declare their length. Sizes are therefore taken on trust to build the
-headers and verified as the bytes go by — a mismatch aborts the install
-before anything is renamed into place.
-"""
-import asyncio
-import tarfile
-from typing import AsyncIterator
-
-from fastapi import UploadFile
-from pydantic import BaseModel, Field
-
-#: Ceilings on one upload. Peak memory is a chunk per concurrent
-#: install; these bound the sandbox's disk and the time a slot is held.
-MAX_FILE_BYTES = 50 * 1024 * 1024
-MAX_TOTAL_BYTES = 500 * 1024 * 1024
-MAX_FILE_COUNT = 100
-MAX_CONCURRENT_INSTALLS = 5
-
-_CHUNK_SIZE = 64 * 1024
-_TAR_BLOCK = 512
-
-#: Serializes installs process-wide, so a burst of uploads cannot
-#: multiply into an unbounded number of open sandbox writes.
-_install_slots = asyncio.Semaphore(MAX_CONCURRENT_INSTALLS)
-
-
-class SkillUploadError(ValueError):
- """Raised when an upload is malformed or over a limit."""
-
-
-class UploadEntry(BaseModel):
- """One file in a folder upload, as the browser described it."""
-
- path: str = Field(
- description=(
- "The file's path relative to the picked folder's parent, "
- "i.e. ``webkitRelativePath``."
- ),
- )
- size: int = Field(ge=0, description="The file's size in bytes.")
-
-
-class UploadManifest(BaseModel):
- """The declared contents of a folder upload."""
-
- entries: list[UploadEntry]
-
-
-def _validate_manifest(manifest: UploadManifest) -> str:
- """Check a manifest and return the skill's root directory name.
-
- Args:
- manifest (`UploadManifest`):
- The declared upload contents.
-
- Returns:
- `str`:
- The single top-level directory every path sits under.
-
- Raises:
- SkillUploadError:
- If a limit is exceeded, a path is unsafe, the paths span
- more than one root, or no ``SKILL.md`` is present.
- """
- entries = manifest.entries
- if not entries:
- raise SkillUploadError("The upload contains no files.")
- if len(entries) > MAX_FILE_COUNT:
- raise SkillUploadError(
- f"A skill may hold at most {MAX_FILE_COUNT} files, "
- f"got {len(entries)}.",
- )
-
- total = 0
- roots: set[str] = set()
- for entry in entries:
- if entry.size > MAX_FILE_BYTES:
- raise SkillUploadError(
- f"{entry.path!r} is {entry.size} bytes, over the "
- f"{MAX_FILE_BYTES}-byte per-file limit.",
- )
- total += entry.size
-
- parts = entry.path.replace("\\", "/").split("/")
- if len(parts) < 2 or any(p in ("", ".", "..") for p in parts):
- raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
- if entry.path.startswith("/"):
- raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
- roots.add(parts[0])
-
- if total > MAX_TOTAL_BYTES:
- raise SkillUploadError(
- f"The upload is {total} bytes, over the "
- f"{MAX_TOTAL_BYTES}-byte limit.",
- )
- if len(roots) != 1:
- raise SkillUploadError(
- f"A skill must be a single folder, got {sorted(roots)}.",
- )
-
- root = roots.pop()
- if not any(e.path == f"{root}/SKILL.md" for e in manifest.entries):
- raise SkillUploadError(
- f"No SKILL.md at the root of {root!r}.",
- )
- return root
-
-
-async def _tar_stream(
- manifest: UploadManifest,
- files: list[UploadFile],
-) -> AsyncIterator[bytes]:
- """Emit a tar of the uploaded files, chunk by chunk.
-
- Args:
- manifest (`UploadManifest`):
- The validated manifest; its order must match ``files``.
- files (`list[UploadFile]`):
- The uploaded parts, in manifest order.
-
- Yields:
- `bytes`:
- The next chunk of the tar archive.
-
- Raises:
- SkillUploadError:
- If a part's real length differs from its declared size.
- """
- for entry, upload in zip(manifest.entries, files):
- info = tarfile.TarInfo(name=entry.path)
- info.size = entry.size
- info.mtime = 0
- yield info.tobuf(tarfile.GNU_FORMAT)
-
- written = 0
- while chunk := await upload.read(_CHUNK_SIZE):
- written += len(chunk)
- if written > entry.size:
- raise SkillUploadError(
- f"{entry.path!r} is larger than its declared "
- f"{entry.size} bytes.",
- )
- yield chunk
-
- if written != entry.size:
- raise SkillUploadError(
- f"{entry.path!r} declared {entry.size} bytes but sent "
- f"{written}.",
- )
- padding = -entry.size % _TAR_BLOCK
- if padding:
- yield b"\0" * padding
-
- # Two zero blocks mark the end of a tar archive.
- yield b"\0" * (2 * _TAR_BLOCK)
diff --git a/src/agentscope/app/_service/_workspace.py b/src/agentscope/app/_service/_workspace.py
new file mode 100644
index 000000000..8ab968c4b
--- /dev/null
+++ b/src/agentscope/app/_service/_workspace.py
@@ -0,0 +1,706 @@
+# -*- coding: utf-8 -*-
+"""Workspace service — resolution, download tokens, uploads, git."""
+import asyncio
+import base64
+import hashlib
+import hmac
+import re
+import tarfile
+import time
+from typing import AsyncIterator, Literal
+
+from fastapi import HTTPException, UploadFile, status
+from pydantic import BaseModel, Field
+
+from ..storage import SessionRecord, StorageBase
+from ..workspace_manager import WorkspaceManagerBase
+from ..._logging import logger
+from ...tool import BackendBase
+from ...workspace import WorkspaceBase
+
+# Long enough to survive a slow round trip and the user's click, short
+# enough that a token leaked through a log or history is already dead.
+DEFAULT_DOWNLOAD_TOKEN_TTL = 60
+
+#: Ceilings on one upload. Peak memory is a chunk per concurrent
+#: install; these bound the sandbox's disk and how long a slot is held.
+MAX_FILE_BYTES = 50 * 1024 * 1024
+MAX_TOTAL_BYTES = 500 * 1024 * 1024
+MAX_FILE_COUNT = 100
+MAX_CONCURRENT_INSTALLS = 5
+
+_CHUNK_SIZE = 64 * 1024
+_TAR_BLOCK = 512
+
+# Long enough for a cold index on a large repository, short enough that
+# a wedged sandbox does not hold the request open.
+_GIT_TIMEOUT_SECS = 5.0
+
+_GIT_STATUS_ARGV: tuple[str, ...] = (
+ "git",
+ # ``git status`` otherwise refreshes and rewrites the index, taking
+ # ``.git/index.lock`` — which the agent's own Bash may be holding.
+ "--no-optional-locks",
+ "status",
+ "--porcelain=v2",
+ "--branch",
+ # NUL-separated, so a path containing a newline cannot split a record.
+ "-z",
+ # Collapse untracked directories; an untracked ``node_modules``
+ # otherwise emits tens of thousands of records.
+ "--untracked-files=normal",
+ "--ignore-submodules=all",
+)
+
+_GIT_SHORTSTAT_ARGV: tuple[str, ...] = (
+ "git",
+ "--no-optional-locks",
+ "diff",
+ "--shortstat",
+ "HEAD",
+)
+
+_INSERTIONS_RE = re.compile(rb"(\d+) insertion")
+_DELETIONS_RE = re.compile(rb"(\d+) deletion")
+_BRANCH_AB_RE = re.compile(r"^\+(\d+) -(\d+)$")
+
+
+class SkillUploadError(ValueError):
+ """Raised when an upload is malformed or over a limit."""
+
+
+class UploadEntry(BaseModel):
+ """One file in a folder upload, as the browser described it."""
+
+ path: str = Field(
+ description=(
+ "The file's path relative to the picked folder's parent, "
+ "i.e. ``webkitRelativePath``."
+ ),
+ )
+ size: int = Field(ge=0, description="The file's size in bytes.")
+
+
+class UploadManifest(BaseModel):
+ """The declared contents of a folder upload."""
+
+ entries: list[UploadEntry]
+
+
+class GitStatus(BaseModel):
+ """Git state of one directory, as shown next to the composer."""
+
+ branch: str | None = Field(
+ default=None,
+ description="Current branch, or null on a detached HEAD.",
+ )
+ head: str | None = Field(
+ default=None,
+ description=(
+ "Full commit SHA of HEAD, or null when the repository has "
+ "no commits yet. Never abbreviated — how many characters to "
+ "show is the caller's decision."
+ ),
+ )
+ ahead: int | None = Field(
+ default=None,
+ description=(
+ "Commits ahead of the upstream branch. Null when no "
+ "upstream is configured, which is a different state from "
+ "zero: git omits the counts entirely in that case."
+ ),
+ )
+ behind: int | None = Field(
+ default=None,
+ description="Commits behind the upstream branch. Null as above.",
+ )
+ insertions: int = Field(
+ default=0,
+ description=(
+ "Lines added relative to HEAD. Untracked files contribute "
+ "nothing — ``git diff`` does not see them — so a session "
+ "that only created files reports zero here and a non-zero "
+ "``untracked``."
+ ),
+ )
+ deletions: int = Field(
+ default=0,
+ description="Lines removed relative to HEAD, same caveat.",
+ )
+ staged: int = Field(default=0, description="Files with staged changes.")
+ unstaged: int = Field(
+ default=0,
+ description="Files with unstaged changes.",
+ )
+ untracked: int = Field(default=0, description="Files git is not tracking.")
+ conflicted: int = Field(
+ default=0,
+ description="Files with unresolved merge conflicts.",
+ )
+
+
+class WorkspaceStatus(BaseModel):
+ """Where a session is pointed, and the git state of that place."""
+
+ workdir: str = Field(
+ description=(
+ "Absolute path of the workspace root. Backend-dependent — a "
+ "host directory locally, a fixed path inside the sandbox "
+ "otherwise — so the client cannot derive it."
+ ),
+ )
+ cwd: str = Field(
+ description=(
+ "Absolute path the session is focused on, resolved from "
+ ":attr:`SessionConfig.cwd`. Equals :attr:`workdir` when that "
+ "is unset."
+ ),
+ )
+ git: GitStatus | None = Field(
+ default=None,
+ description=(
+ "Git state of :attr:`cwd`, or null when there is none to "
+ "report — not a repository, git unavailable, the command "
+ "timed out, or the backend could not run it. The caller "
+ "shows no branch either way, so the reasons are logged "
+ "rather than returned."
+ ),
+ )
+
+
+class WorkspaceService:
+ """Everything behind ``/workspace/*`` that is not HTTP plumbing.
+
+ Args:
+ storage (`StorageBase`):
+ Persistent storage, used to look session records up.
+ workspace_manager (`WorkspaceManagerBase`):
+ Opens or reattaches the workspace behind a session.
+ download_secret (`str`):
+ App-wide secret backing the download capability tokens.
+ """
+
+ def __init__(
+ self,
+ storage: StorageBase,
+ workspace_manager: WorkspaceManagerBase,
+ download_secret: str,
+ ) -> None:
+ """Bind dependencies."""
+ self._storage = storage
+ self._workspace_manager = workspace_manager
+ self._download_secret = download_secret
+ #: Serializes installs, so a burst cannot multiply into an
+ #: unbounded number of open sandbox writes.
+ self._install_slots = asyncio.Semaphore(MAX_CONCURRENT_INSTALLS)
+
+ async def resolve(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ ) -> WorkspaceBase:
+ """Return the workspace backing a session.
+
+ Args:
+ user_id (`str`): The authenticated user ID.
+ agent_id (`str`): The agent owning the session.
+ session_id (`str`): The session to resolve.
+
+ Returns:
+ `WorkspaceBase`: The session's workspace.
+
+ Raises:
+ `HTTPException`: 404 when the session does not exist.
+ """
+ _, workspace = await self._resolve_record(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ return workspace
+
+ async def read_status(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ ) -> WorkspaceStatus:
+ """Report where a session sits and the git state of that place.
+
+ Args:
+ user_id (`str`): The authenticated user ID.
+ agent_id (`str`): The agent owning the session.
+ session_id (`str`): The session to report on.
+
+ Returns:
+ `WorkspaceStatus`: The workspace root, the resolved
+ directory, and its git summary when there is one.
+
+ Raises:
+ `HTTPException`: 404 when the session does not exist.
+ """
+ record, workspace = await self._resolve_record(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ backend = workspace.get_backend()
+ # Stored as the user gave it: absolute, relative to a root the
+ # client cannot see, or unset for the root itself.
+ cwd = backend.abspath(record.config.cwd or "", cwd=workspace.workdir)
+ return WorkspaceStatus(
+ workdir=workspace.workdir,
+ cwd=cwd,
+ git=await self._read_git(backend, cwd),
+ )
+
+ async def _resolve_record(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ ) -> tuple[SessionRecord, WorkspaceBase]:
+ """Load a session and open the workspace it is bound to.
+
+ Args:
+ user_id (`str`): The authenticated user ID.
+ agent_id (`str`): The agent owning the session.
+ session_id (`str`): The session to resolve.
+
+ Returns:
+ `tuple[SessionRecord, WorkspaceBase]`: The record and its
+ workspace.
+
+ Raises:
+ `HTTPException`: 404 when the session does not exist.
+ """
+ session_record = await self._storage.get_session(
+ user_id,
+ agent_id,
+ session_id,
+ )
+ if session_record is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Session {session_id!r} not found.",
+ )
+ workspace = await self._workspace_manager.get_workspace(
+ user_id,
+ agent_id,
+ session_id,
+ session_record.config.workspace_id,
+ )
+ return session_record, workspace
+
+ # ── Download tokens ────────────────────────────────────────────────
+ #
+ # A browser only streams to disk when it issues the request itself,
+ # and such a request carries no custom header — so the credential
+ # travels in the URL as a capability: this user, this path, briefly.
+
+ def sign_download_token(
+ self,
+ user_id: str,
+ path: str,
+ ttl: int = DEFAULT_DOWNLOAD_TOKEN_TTL,
+ ) -> tuple[str, int]:
+ """Mint a token authorizing one download.
+
+ Args:
+ user_id (`str`): The already-authenticated caller.
+ path (`str`): The path the token authorizes, verbatim as
+ the download request will send it.
+ ttl (`int`, defaults to 60): Seconds the token stays valid.
+
+ Returns:
+ `tuple[str, int]`: The token and its expiry as a Unix
+ timestamp.
+ """
+ expires_at = int(time.time()) + ttl
+ signature = self._signature(expires_at, user_id, path)
+ token = (
+ f"{expires_at}"
+ f".{self._b64(user_id.encode('utf-8'))}"
+ f".{self._b64(signature)}"
+ )
+ return token, expires_at
+
+ def verify_download_token(self, token: str, path: str) -> str:
+ """Return the user a token was granted to, for this path.
+
+ The path is not read out of the token but re-derived from the
+ request, so a token for one file cannot be replayed against
+ another.
+
+ Args:
+ token (`str`): The token from the request.
+ path (`str`): The path the request is asking for.
+
+ Returns:
+ `str`: The user ID the token was minted for.
+
+ Raises:
+ `ValueError`: The token is malformed, expired, or does not
+ match.
+ """
+ try:
+ raw_expiry, raw_user, raw_signature = token.split(".")
+ expires_at = int(raw_expiry)
+ user_id = self._unb64(raw_user).decode("utf-8")
+ signature = self._unb64(raw_signature)
+ except (ValueError, UnicodeDecodeError) as e:
+ raise ValueError("Malformed download token.") from e
+
+ expected = self._signature(expires_at, user_id, path)
+ if not hmac.compare_digest(signature, expected):
+ raise ValueError("Invalid download token.")
+ if expires_at < time.time():
+ raise ValueError("Expired download token.")
+ return user_id
+
+ def _signature(self, expires_at: int, user_id: str, path: str) -> bytes:
+ """Compute the MAC binding an expiry, a user and a path.
+
+ ``\\0`` separates the fields because it cannot occur in any of
+ them, so no combination can be re-cut into a different triple.
+
+ Args:
+ expires_at (`int`): Unix timestamp after which to refuse.
+ user_id (`str`): The user the capability was granted to.
+ path (`str`): The one path the capability covers.
+
+ Returns:
+ `bytes`: The raw HMAC-SHA256 digest.
+ """
+ message = f"{expires_at}\0{user_id}\0{path}".encode("utf-8")
+ return hmac.new(
+ self._download_secret.encode("utf-8"),
+ message,
+ hashlib.sha256,
+ ).digest()
+
+ @staticmethod
+ def _b64(raw: bytes) -> str:
+ """Encode without padding, which is not URL-safe to round-trip."""
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+ @staticmethod
+ def _unb64(text: str) -> bytes:
+ """Reverse :meth:`_b64`, restoring the stripped padding."""
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
+
+ # ── Skill upload ───────────────────────────────────────────────────
+ #
+ # A tar header needs each member's size before its bytes, and
+ # multipart parts do not declare one — hence the manifest, trusted
+ # to build the headers and verified as the bytes go by.
+
+ @staticmethod
+ def validate_manifest(manifest: UploadManifest, file_count: int) -> str:
+ """Check a manifest and return the skill's root directory name.
+
+ Args:
+ manifest (`UploadManifest`): The declared upload contents.
+ file_count (`int`): How many parts actually arrived.
+
+ Returns:
+ `str`: The single top-level directory every path sits under.
+
+ Raises:
+ SkillUploadError: If a limit is exceeded, a path is unsafe,
+ the paths span more than one root, no ``SKILL.md`` is
+ present, or the parts do not match the manifest.
+ """
+ entries = manifest.entries
+ if not entries:
+ raise SkillUploadError("The upload contains no files.")
+ if file_count != len(entries):
+ raise SkillUploadError(
+ f"The manifest lists {len(entries)} files but "
+ f"{file_count} were sent.",
+ )
+ if len(entries) > MAX_FILE_COUNT:
+ raise SkillUploadError(
+ f"A skill may hold at most {MAX_FILE_COUNT} files, "
+ f"got {len(entries)}.",
+ )
+
+ total = 0
+ roots: set[str] = set()
+ for entry in entries:
+ if entry.size > MAX_FILE_BYTES:
+ raise SkillUploadError(
+ f"{entry.path!r} is {entry.size} bytes, over the "
+ f"{MAX_FILE_BYTES}-byte per-file limit.",
+ )
+ total += entry.size
+
+ parts = entry.path.replace("\\", "/").split("/")
+ if len(parts) < 2 or any(p in ("", ".", "..") for p in parts):
+ raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
+ if entry.path.startswith("/"):
+ raise SkillUploadError(f"Unsafe upload path: {entry.path!r}")
+ roots.add(parts[0])
+
+ if total > MAX_TOTAL_BYTES:
+ raise SkillUploadError(
+ f"The upload is {total} bytes, over the "
+ f"{MAX_TOTAL_BYTES}-byte limit.",
+ )
+ if len(roots) != 1:
+ raise SkillUploadError(
+ f"A skill must be a single folder, got {sorted(roots)}.",
+ )
+
+ root = roots.pop()
+ if not any(e.path == f"{root}/SKILL.md" for e in manifest.entries):
+ raise SkillUploadError(f"No SKILL.md at the root of {root!r}.")
+ return root
+
+ async def install_skill(
+ self,
+ workspace: WorkspaceBase,
+ stream: AsyncIterator[bytes],
+ archive_format: Literal["zip", "tar", "tar.gz"],
+ name: str,
+ ) -> None:
+ """Pipe a skill archive into a workspace, one install at a time.
+
+ Takes the workspace rather than a session, because the
+ from-library path resolves once and then installs several.
+
+ Args:
+ workspace (`WorkspaceBase`): The target workspace.
+ stream (`AsyncIterator[bytes]`): The archive's bytes.
+ archive_format (`Literal["zip", "tar", "tar.gz"]`): How the
+ stream is packed.
+ name (`str`): The skill's name, for the backend's logging.
+ """
+ async with self._install_slots:
+ await workspace.add_skill_archive(stream, archive_format, name)
+
+ @staticmethod
+ async def tar_stream(
+ manifest: UploadManifest,
+ files: list[UploadFile],
+ ) -> AsyncIterator[bytes]:
+ """Emit a tar of the uploaded files, chunk by chunk.
+
+ Args:
+ manifest (`UploadManifest`): The validated manifest.
+ files (`list[UploadFile]`): The parts, in manifest order.
+
+ Yields:
+ `bytes`: The next chunk of the tar archive.
+
+ Raises:
+ SkillUploadError: If a part's real length differs from its
+ declared size.
+ """
+ for entry, upload in zip(manifest.entries, files):
+ info = tarfile.TarInfo(name=entry.path)
+ info.size = entry.size
+ info.mtime = 0
+ yield info.tobuf(tarfile.GNU_FORMAT)
+
+ written = 0
+ while chunk := await upload.read(_CHUNK_SIZE):
+ written += len(chunk)
+ if written > entry.size:
+ raise SkillUploadError(
+ f"{entry.path!r} is larger than its declared "
+ f"{entry.size} bytes.",
+ )
+ yield chunk
+
+ if written != entry.size:
+ raise SkillUploadError(
+ f"{entry.path!r} declared {entry.size} bytes but "
+ f"sent {written}.",
+ )
+ padding = -entry.size % _TAR_BLOCK
+ if padding:
+ yield b"\0" * padding
+
+ # Two zero blocks mark the end of a tar archive.
+ yield b"\0" * (2 * _TAR_BLOCK)
+
+ # ── Git status ─────────────────────────────────────────────────────
+
+ async def _read_git(
+ self,
+ backend: BackendBase,
+ cwd: str,
+ ) -> GitStatus | None:
+ """Summarise the git state of ``cwd``, or return ``None``.
+
+ Two argv invocations rather than one shell line: ``exec_shell``
+ runs argv directly, so chaining would mean wrapping in
+ ``/bin/sh``, which a Windows ``LocalBackend`` does not have.
+ Keeping them apart also means a failing ``diff`` still leaves
+ the branch on screen.
+
+ Never raises. A directory that is not a repository is the
+ ordinary case, and the backends disagree on how they report
+ trouble — Docker and K8s raise transport errors out of
+ ``exec_shell`` while the others fold everything into a non-zero
+ result — so every failure reads as "nothing to report".
+
+ Args:
+ backend (`BackendBase`): The workspace's backend; the only
+ way into a sandbox.
+ cwd (`str`): Absolute directory to inspect.
+
+ Returns:
+ `GitStatus | None`: The summary, or ``None`` when git had
+ nothing to say.
+ """
+ try:
+ status_result = await backend.exec_shell(
+ list(_GIT_STATUS_ARGV),
+ cwd=cwd,
+ timeout=_GIT_TIMEOUT_SECS,
+ )
+ except Exception as exc: # pylint: disable=broad-except
+ logger.debug("git status failed in %s: %s", cwd, exc)
+ return None
+
+ if not status_result.ok():
+ # 128 not a repository, 127 no git binary or bad cwd, -1
+ # timeout. None distinguishable enough to explain to a user.
+ logger.debug(
+ "git status exited %d in %s",
+ status_result.exit_code,
+ cwd,
+ )
+ return None
+
+ summary = self._parse_porcelain_v2(status_result.stdout)
+ if summary.branch is None and summary.head is None:
+ # Real git always names one or the other — a detached HEAD
+ # has a commit, an unborn branch has a name.
+ logger.debug("git status gave no branch in %s", cwd)
+ return None
+
+ try:
+ diff_result = await backend.exec_shell(
+ list(_GIT_SHORTSTAT_ARGV),
+ cwd=cwd,
+ timeout=_GIT_TIMEOUT_SECS,
+ )
+ except Exception as exc: # pylint: disable=broad-except
+ logger.debug("git diff failed in %s: %s", cwd, exc)
+ return summary
+
+ if not diff_result.ok():
+ # Expected on a repository with no commits, where HEAD is
+ # unborn.
+ return summary
+
+ insertions, deletions = self._parse_shortstat(diff_result.stdout)
+ return summary.model_copy(
+ update={"insertions": insertions, "deletions": deletions},
+ )
+
+ @staticmethod
+ def _parse_porcelain_v2(stdout: bytes) -> GitStatus:
+ """Parse ``git status --porcelain=v2 --branch -z`` output.
+
+ Line counts are left at zero; they come from the separate
+ ``--shortstat`` run.
+
+ Args:
+ stdout (`bytes`): Raw stdout. Unparseable records are
+ skipped rather than raising: a status that omits one odd
+ entry is still worth showing.
+
+ Returns:
+ `GitStatus`: Branch, upstream divergence and file counts.
+ """
+ branch: str | None = None
+ head: str | None = None
+ ahead: int | None = None
+ behind: int | None = None
+ staged = unstaged = untracked = conflicted = 0
+
+ chunks = stdout.split(b"\0")
+ index = 0
+ while index < len(chunks):
+ chunk = chunks[index]
+ index += 1
+ if not chunk:
+ continue
+
+ record = chunk.decode("utf-8", errors="replace")
+ kind, _, rest = record.partition(" ")
+
+ if kind == "#":
+ key, _, value = rest.partition(" ")
+ if key == "branch.oid":
+ head = None if value == "(initial)" else value
+ elif key == "branch.head":
+ branch = None if value == "(detached)" else value
+ elif key == "branch.ab":
+ match = _BRANCH_AB_RE.match(value)
+ if match:
+ ahead = int(match.group(1))
+ behind = int(match.group(2))
+ continue
+
+ if kind == "?":
+ untracked += 1
+ continue
+
+ if kind == "u":
+ # An unmerged entry's XY is the conflict pair, not a
+ # staged/unstaged pair, so it counts only as conflicted.
+ conflicted += 1
+ continue
+
+ if kind not in ("1", "2"):
+ continue
+
+ if kind == "2":
+ # In -z mode a rename's original path is its own
+ # NUL-separated field, so this record spans two chunks.
+ index += 1
+
+ xy = rest.split(" ", 1)[0]
+ if len(xy) != 2:
+ continue
+ # ``MM`` counts on both sides — the two are not additive.
+ if xy[0] != ".":
+ staged += 1
+ if xy[1] != ".":
+ unstaged += 1
+
+ return GitStatus(
+ branch=branch,
+ head=head,
+ ahead=ahead,
+ behind=behind,
+ staged=staged,
+ unstaged=unstaged,
+ untracked=untracked,
+ conflicted=conflicted,
+ )
+
+ @staticmethod
+ def _parse_shortstat(stdout: bytes) -> tuple[int, int]:
+ """Parse ``git diff --shortstat`` into insertions and deletions.
+
+ Args:
+ stdout (`bytes`): Raw stdout, e.g. ``" 2 files changed, 15
+ insertions(+)"``. Either clause is absent when its count
+ is zero, and the line is empty for a clean tree.
+
+ Returns:
+ `tuple[int, int]`: Counts, zero for whatever git omitted.
+ """
+ insertions = _INSERTIONS_RE.search(stdout)
+ deletions = _DELETIONS_RE.search(stdout)
+ return (
+ int(insertions.group(1)) if insertions else 0,
+ int(deletions.group(1)) if deletions else 0,
+ )
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index 7f746d243..3be59c79e 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -18,6 +18,7 @@ from ._service import (
KnowledgeBaseService,
ResourceAccessService,
SessionService,
+ WorkspaceService,
)
from ._types import AgentMiddlewareFactory, AgentToolFactory
from .hub import MCPHubBase, SkillHubBase
@@ -119,6 +120,18 @@ async def get_session_service(request: Request) -> SessionService:
return request.app.state.session_service
+async def get_workspace_service(request: Request) -> WorkspaceService:
+ """Return the application-wide workspace service.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+
+ Returns:
+ `WorkspaceService`: The instance stored in ``app.state``.
+ """
+ return request.app.state.workspace_service
+
+
async def get_chat_run_registry(request: Request) -> ChatRunRegistry:
"""Return the per-process chat-run registry.
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index 58964d9e5..1fe2ec795 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -131,6 +131,35 @@ class SessionConfig(BaseModel):
)
"""The session display name."""
+ cwd: str | None = Field(
+ default=None,
+ description=(
+ "Directory the session is focused on — absolute, or "
+ "relative to the workspace root. ``None`` means the root."
+ ),
+ )
+ """The directory this session is currently focused on.
+
+ Not confined to the workspace root, matching
+ ``GET /workspace/directories``: on a sandboxed backend the
+ reachable filesystem *is* the sandbox, and on a local one the
+ caller is already trusted with the host. Nothing is validated on
+ write — the value only names a place to look, so a path that has
+ gone missing surfaces when something tries to read it rather than
+ blocking the change.
+
+ A relative value stays relative on purpose: the workspace root is
+ backend-dependent (a host directory for :class:`LocalWorkspace`, a
+ fixed in-sandbox path for the container backends) and only
+ resolvable asynchronously, so denormalising it here would go stale
+ the moment a session moves between backends. Resolve with
+ ``backend.abspath(cwd, cwd=workspace.workdir)`` at the point of use
+ — which handles both forms.
+
+ Purely a viewing anchor: it does **not** change where ``Bash``,
+ ``Glob`` or ``Grep`` execute.
+ """
+
chat_model_config: ChatModelConfig | None = None
"""The chat model config. None means no model has been configured yet."""
diff --git a/tests/service_git_status_parse_test.py b/tests/service_git_status_parse_test.py
new file mode 100644
index 000000000..348fa9ccf
--- /dev/null
+++ b/tests/service_git_status_parse_test.py
@@ -0,0 +1,242 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Git status parser test case — pure functions, no git binary needed.
+
+``porcelain=v2`` is a stable documented format, but three of its corners
+are easy to get wrong and each is asserted below: a rename record spans
+two NUL-separated fields under ``-z``, ``branch.ab`` is absent rather
+than zero when no upstream is configured, and an ``MM`` entry counts on
+both the staged and the unstaged side.
+"""
+from unittest import TestCase
+
+from agentscope.app._service import WorkspaceService
+
+# A plausible blob/mode run; the parser only reads the XY field, but
+# using realistic records keeps the fixtures honest.
+_TRAILER = "N... 100644 100644 100644 1111111 2222222"
+
+
+def _records(*records: str) -> bytes:
+ """Join records the way ``-z`` does: NUL-separated and terminated."""
+ return ("\0".join(records) + "\0").encode("utf-8")
+
+
+class ParsePorcelainV2Test(TestCase):
+ """Branch headers and per-file counting."""
+
+ def test_clean_tree_with_upstream(self) -> None:
+ """A clean tree in sync reports zeroes, not nulls."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(
+ "# branch.oid abc123def456",
+ "# branch.head main",
+ "# branch.upstream origin/main",
+ "# branch.ab +0 -0",
+ ),
+ )
+
+ self.assertEqual(status.branch, "main")
+ self.assertEqual(status.head, "abc123def456")
+ self.assertEqual(status.ahead, 0)
+ self.assertEqual(status.behind, 0)
+ self.assertEqual(status.staged, 0)
+ self.assertEqual(status.unstaged, 0)
+
+ def test_no_upstream_reports_none_not_zero(self) -> None:
+ """Without an upstream git omits ``branch.ab`` entirely.
+
+ ``None`` and ``0`` mean different things to the caller — no
+ upstream to compare against versus level with one — so the
+ absent line must not collapse into a count.
+ """
+ status = WorkspaceService._parse_porcelain_v2(
+ _records("# branch.oid abc123", "# branch.head feature/x"),
+ )
+
+ self.assertEqual(status.branch, "feature/x")
+ self.assertIsNone(status.ahead)
+ self.assertIsNone(status.behind)
+
+ def test_ahead_and_behind_are_read_separately(self) -> None:
+ """``+2 -3`` is two counts, not a single signed number."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(
+ "# branch.oid abc123",
+ "# branch.head main",
+ "# branch.ab +2 -3",
+ ),
+ )
+
+ self.assertEqual(status.ahead, 2)
+ self.assertEqual(status.behind, 3)
+
+ def test_detached_head_has_no_branch(self) -> None:
+ """A detached HEAD reports its commit but no branch name."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records("# branch.oid deadbeef", "# branch.head (detached)"),
+ )
+
+ self.assertIsNone(status.branch)
+ self.assertEqual(status.head, "deadbeef")
+
+ def test_unborn_branch_has_no_head(self) -> None:
+ """A repository with no commits names a branch but no commit."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records("# branch.oid (initial)", "# branch.head main"),
+ )
+
+ self.assertEqual(status.branch, "main")
+ self.assertIsNone(status.head)
+
+ def test_worktree_change_counts_as_unstaged_only(self) -> None:
+ """``.M`` is modified in the worktree but not in the index."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(f"1 .M {_TRAILER} a.py"),
+ )
+
+ self.assertEqual(status.staged, 0)
+ self.assertEqual(status.unstaged, 1)
+
+ def test_index_change_counts_as_staged_only(self) -> None:
+ """``M.`` is staged with a clean worktree."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(f"1 M. {_TRAILER} a.py"),
+ )
+
+ self.assertEqual(status.staged, 1)
+ self.assertEqual(status.unstaged, 0)
+
+ def test_partially_staged_file_counts_on_both_sides(self) -> None:
+ """``MM`` is one file that is both staged and modified since.
+
+ The two counts describe the same file from different angles, so
+ a caller must never add them together.
+ """
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(f"1 MM {_TRAILER} a.py"),
+ )
+
+ self.assertEqual(status.staged, 1)
+ self.assertEqual(status.unstaged, 1)
+
+ def test_rename_consumes_its_original_path_field(self) -> None:
+ """Under ``-z`` a rename's old path is its own NUL field.
+
+ The old path here is named ``? old.py`` — legal on POSIX, and
+ exactly what ``-z`` exists to survive. Left unconsumed it reads
+ as an untracked record and inflates the count, which is why the
+ assertion below is on ``untracked`` rather than on the rename.
+ """
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(
+ f"2 R. {_TRAILER} R100 new.py",
+ "? old.py",
+ f"1 .M {_TRAILER} b.py",
+ ),
+ )
+
+ self.assertEqual(status.staged, 1)
+ self.assertEqual(status.unstaged, 1)
+ self.assertEqual(status.untracked, 0)
+
+ def test_unmerged_counts_as_conflicted_only(self) -> None:
+ """``u UU``'s XY is a conflict pair, not a staged/unstaged one."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records("u UU N... 100644 100644 100644 100644 a b c x.py"),
+ )
+
+ self.assertEqual(status.conflicted, 1)
+ self.assertEqual(status.staged, 0)
+ self.assertEqual(status.unstaged, 0)
+
+ def test_untracked_entries_are_counted(self) -> None:
+ """Untracked files and collapsed directories both count once."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records("? notes.md", "? scratch/"),
+ )
+
+ self.assertEqual(status.untracked, 2)
+ self.assertEqual(status.unstaged, 0)
+
+ def test_paths_with_spaces_and_newlines_survive(self) -> None:
+ """``-z`` is what makes an awkward filename safe to parse."""
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(
+ f"1 .M {_TRAILER} my docs/a b.py",
+ "? line\nbreak.txt",
+ ),
+ )
+
+ self.assertEqual(status.unstaged, 1)
+ self.assertEqual(status.untracked, 1)
+
+ def test_unknown_record_types_are_skipped(self) -> None:
+ """An unrecognised prefix is ignored, not fatal.
+
+ Reporting a status that omits one odd entry beats reporting none
+ at all if git grows a record type.
+ """
+ status = WorkspaceService._parse_porcelain_v2(
+ _records(
+ "! ignored.txt",
+ "x whatever",
+ f"1 .M {_TRAILER} a.py",
+ ),
+ )
+
+ self.assertEqual(status.unstaged, 1)
+
+ def test_truncated_output_does_not_raise(self) -> None:
+ """A cut-off final record is dropped rather than crashing."""
+ truncated = _records(f"1 .M {_TRAILER} a.py") + b"1 M"
+
+ status = WorkspaceService._parse_porcelain_v2(truncated)
+
+ self.assertEqual(status.unstaged, 1)
+
+ def test_empty_output(self) -> None:
+ """No output at all yields a blank, valid status."""
+ status = WorkspaceService._parse_porcelain_v2(b"")
+
+ self.assertIsNone(status.branch)
+ self.assertEqual(status.staged, 0)
+
+
+class ParseShortstatTest(TestCase):
+ """``git diff --shortstat`` line counts."""
+
+ def test_insertions_and_deletions(self) -> None:
+ """The usual case with both clauses present."""
+ line = b" 20 files changed, 621 insertions(+), 182 deletions(-)\n"
+
+ self.assertEqual(WorkspaceService._parse_shortstat(line), (621, 182))
+
+ def test_insertions_only(self) -> None:
+ """Git omits the deletions clause when nothing was removed."""
+ line = b" 1 file changed, 3 insertions(+)\n"
+
+ self.assertEqual(WorkspaceService._parse_shortstat(line), (3, 0))
+
+ def test_deletions_only(self) -> None:
+ """And omits insertions likewise."""
+ line = b" 1 file changed, 4 deletions(-)\n"
+
+ self.assertEqual(WorkspaceService._parse_shortstat(line), (0, 4))
+
+ def test_singular_wording(self) -> None:
+ """One line reads ``insertion(+)``, without the plural s."""
+ line = b" 1 file changed, 1 insertion(+), 1 deletion(-)\n"
+
+ self.assertEqual(WorkspaceService._parse_shortstat(line), (1, 1))
+
+ def test_clean_tree_is_empty_output(self) -> None:
+ """Nothing changed means no line at all, not a line of zeroes."""
+ self.assertEqual(WorkspaceService._parse_shortstat(b""), (0, 0))
+
+ def test_unrecognised_output(self) -> None:
+ """Anything unparseable reads as no change rather than raising."""
+ self.assertEqual(
+ WorkspaceService._parse_shortstat(b"fatal: bad revision 'HEAD'"),
+ (0, 0),
+ )
diff --git a/tests/service_workspace_files_test.py b/tests/service_workspace_files_test.py
index 0bf4fec4f..aeea0414a 100644
--- a/tests/service_workspace_files_test.py
+++ b/tests/service_workspace_files_test.py
@@ -20,10 +20,7 @@ from agentscope.app._router._workspace import (
list_workspace_directory,
read_workspace_file,
)
-from agentscope.app._service._download_token import (
- sign_download_token,
- verify_download_token,
-)
+from agentscope.app._service import WorkspaceService
from agentscope.app.storage import (
AgentData,
AgentRecord,
@@ -250,38 +247,50 @@ async def _collect(response: object) -> bytes:
class DownloadTokenTests(IsolatedAsyncioTestCase):
"""Unit tests for the capability token itself."""
+ def setUp(self) -> None:
+ """A service bound to the test secret; storage is never touched."""
+ self.service = WorkspaceService(None, None, SECRET)
+ self.other = WorkspaceService(None, None, "other-secret")
+
def test_roundtrip_returns_the_user(self) -> None:
"""A freshly minted token verifies back to who it was for."""
- token, expires_at = sign_download_token(SECRET, "alice", "/w/a.txt")
+ token, expires_at = self.service.sign_download_token(
+ "alice",
+ "/w/a.txt",
+ )
self.assertGreater(expires_at, time.time())
self.assertEqual(
- verify_download_token(SECRET, token, "/w/a.txt"),
+ self.service.verify_download_token(token, "/w/a.txt"),
"alice",
)
def test_token_does_not_cover_another_path(self) -> None:
"""The path is re-derived from the request, so replay fails."""
- token, _ = sign_download_token(SECRET, "alice", "/w/a.txt")
+ token, _ = self.service.sign_download_token("alice", "/w/a.txt")
with self.assertRaises(ValueError):
- verify_download_token(SECRET, token, "/w/secret.txt")
+ self.service.verify_download_token(token, "/w/secret.txt")
def test_another_secret_is_rejected(self) -> None:
"""A token minted elsewhere must not verify here."""
- token, _ = sign_download_token("other-secret", "alice", "/w/a.txt")
+ token, _ = self.other.sign_download_token("alice", "/w/a.txt")
with self.assertRaises(ValueError):
- verify_download_token(SECRET, token, "/w/a.txt")
+ self.service.verify_download_token(token, "/w/a.txt")
def test_expired_token_is_rejected(self) -> None:
"""A TTL that has already passed makes the token useless."""
- token, _ = sign_download_token(SECRET, "alice", "/w/a.txt", ttl=-1)
+ token, _ = self.service.sign_download_token(
+ "alice",
+ "/w/a.txt",
+ ttl=-1,
+ )
with self.assertRaises(ValueError):
- verify_download_token(SECRET, token, "/w/a.txt")
+ self.service.verify_download_token(token, "/w/a.txt")
def test_garbage_is_rejected(self) -> None:
"""Malformed input must raise, not crash with an index error."""
for bad in ("", "not-a-token", "1.2", "x.y.z", "9999999999.YQ.YQ"):
with self.assertRaises(ValueError):
- verify_download_token(SECRET, bad, "/w/a.txt")
+ self.service.verify_download_token(bad, "/w/a.txt")
# ---------------------------------------------------------------------------
@@ -302,6 +311,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
self._workspace = _FakeWorkspace(self._backend)
self._wm = _FakeWorkspaceManager(self._workspace)
self._storage = _FakeStorage([_make_session()])
+ self._service = WorkspaceService(self._storage, self._wm, SECRET)
# ------------------------------------------------------------------
# directories
@@ -309,15 +319,15 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
async def test_list_root(self) -> None:
"""The workspace root lists its seeded files and directories."""
- entries = await list_workspace_directory(
+ listing = await list_workspace_directory(
agent_id="a",
session_id="s",
path="",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
- by_name = {e.name: e for e in entries}
+ self.assertEqual(listing.path, "/workspace")
+ by_name = {e.name: e for e in listing.entries}
self.assertEqual(sorted(by_name), ["notes.txt", "subdir"])
self.assertFalse(by_name["notes.txt"].is_dir)
self.assertEqual(by_name["notes.txt"].size_bytes, len(b"hello world"))
@@ -330,39 +340,36 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
async def test_relative_path_resolves_against_workdir(self) -> None:
"""A relative path is still convenient, and still works."""
- entries = await list_workspace_directory(
+ listing = await list_workspace_directory(
agent_id="a",
session_id="s",
path="subdir",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
- self.assertEqual([e.name for e in entries], ["report.md"])
+ self.assertEqual([e.name for e in listing.entries], ["report.md"])
async def test_absolute_path_outside_workspace_is_allowed(self) -> None:
"""Browsing is not confined to the workspace root."""
- entries = await list_workspace_directory(
+ listing = await list_workspace_directory(
agent_id="a",
session_id="s",
path="/elsewhere",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
- self.assertEqual([e.name for e in entries], ["outside.txt"])
+ self.assertEqual([e.name for e in listing.entries], ["outside.txt"])
async def test_parent_traversal_is_allowed(self) -> None:
"""``..`` is an ordinary path component now, not an attack."""
- entries = await list_workspace_directory(
+ listing = await list_workspace_directory(
agent_id="a",
session_id="s",
path="../elsewhere",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
- self.assertEqual([e.name for e in entries], ["outside.txt"])
+ self.assertEqual([e.name for e in listing.entries], ["outside.txt"])
async def test_missing_session_raises_404(self) -> None:
"""An unknown session id must return a 404 HTTP error."""
@@ -372,8 +379,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="does-not-exist",
path="",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
self.assertEqual(ctx.exception.status_code, status.HTTP_404_NOT_FOUND)
@@ -385,8 +391,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="s",
path="missing-dir",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
self.assertEqual(ctx.exception.status_code, status.HTTP_404_NOT_FOUND)
@@ -398,8 +403,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="s",
path="notes.txt",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
+ workspace_service=self._service,
)
self.assertEqual(
ctx.exception.status_code,
@@ -415,9 +419,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
return await read_workspace_file(
agent_id="a",
session_id="s",
- storage=self._storage,
- workspace_manager=self._wm,
- secret=SECRET,
+ workspace_service=self._service,
**kwargs,
)
@@ -519,9 +521,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="s",
path="notes.txt",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
- secret=SECRET,
+ workspace_service=self._service,
)
# Sent back exactly as minted — the token binds the query
# string, since resolving it needs the user it has yet to yield.
@@ -540,9 +540,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="s",
path="notes.txt",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
- secret=SECRET,
+ workspace_service=self._service,
)
with self.assertRaises(HTTPException) as ctx:
await self._read(
@@ -563,9 +561,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
session_id="s",
path="notes.txt",
user_id="u",
- storage=self._storage,
- workspace_manager=self._wm,
- secret=SECRET,
+ workspace_service=self._service,
)
with self.assertRaises(HTTPException) as ctx:
await self._read(
@@ -581,7 +577,7 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):
async def test_tampered_token_raises_401(self) -> None:
"""An edited signature must not pass."""
- token, _ = sign_download_token(SECRET, "u", "notes.txt")
+ token, _ = self._service.sign_download_token("u", "notes.txt")
with self.assertRaises(HTTPException) as ctx:
await self._read(
path="notes.txt",
diff --git a/tests/service_workspace_status_test.py b/tests/service_workspace_status_test.py
new file mode 100644
index 000000000..61a68de78
--- /dev/null
+++ b/tests/service_workspace_status_test.py
@@ -0,0 +1,305 @@
+# -*- coding: utf-8 -*-
+"""``GET /workspace/status`` test case.
+
+The endpoint's whole job beyond composing a response is refusing to fail
+loudly. ``exec_shell`` reports trouble inconsistently across backends —
+Docker and K8s raise, the rest fold everything into a non-zero
+``ExecResult`` — and a directory that is simply not a repository is the
+common case, not an error. Every one of those paths is asserted to yield
+``git: null`` with the rest of the response intact.
+
+Dependencies are injected by calling the endpoint coroutine directly, so
+no app, no git binary and no real filesystem are involved.
+"""
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+from fastapi import HTTPException, status
+
+from agentscope.agent import ContextConfig, ReActConfig
+from agentscope.app._router._workspace import get_workspace_status
+from agentscope.app._service import WorkspaceService
+from agentscope.app.storage import (
+ AgentData,
+ AgentRecord,
+ SessionConfig,
+ SessionRecord,
+ SessionSource,
+)
+from agentscope.state import AgentState
+from agentscope.tool import ExecResult
+
+_STATUS_STDOUT = (
+ b"# branch.oid abc123\0"
+ b"# branch.head main\0"
+ b"# branch.upstream origin/main\0"
+ b"# branch.ab +2 -1\0"
+ b"1 .M N... 100644 100644 100644 111 222 a.py\0"
+ b"? notes.md\0"
+)
+_SHORTSTAT_STDOUT = b" 1 file changed, 15 insertions(+), 20 deletions(-)\n"
+
+
+class _FakeBackend:
+ """Answers the two git invocations from a canned script."""
+
+ def __init__(self, *results: Any) -> None:
+ # Each entry is either an ExecResult to return or an exception
+ # to raise, consumed in call order.
+ self._results = list(results)
+ self.calls: list[tuple[list[str], str | None]] = []
+
+ def abspath(self, path: str, *, cwd: str) -> str:
+ """Resolve like posixpath, which is what the real backends use."""
+ if path.startswith("/"):
+ return path
+ return f"{cwd}/{path}".rstrip("/") if path else cwd
+
+ async def exec_shell(
+ self,
+ command: list[str],
+ *,
+ cwd: str | None = None,
+ timeout: float | None = None,
+ ) -> ExecResult:
+ """Return or raise the next scripted outcome."""
+ _ = timeout
+ self.calls.append((command, cwd))
+ outcome = self._results.pop(0)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+
+class _FakeWorkspace:
+ def __init__(self, backend: _FakeBackend) -> None:
+ self.workdir = "/workspace"
+ self._backend = backend
+
+ def get_backend(self) -> _FakeBackend:
+ """Expose the injected backend."""
+ return self._backend
+
+
+class _FakeWorkspaceManager:
+ def __init__(self, workspace: _FakeWorkspace) -> None:
+ self._ws = workspace
+
+ async def get_workspace(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ workspace_id: str | None = None,
+ ) -> _FakeWorkspace:
+ """Return the pre-seeded workspace, ignoring identifier args."""
+ _ = (user_id, agent_id, session_id, workspace_id)
+ return self._ws
+
+
+class _FakeStorage:
+ def __init__(self, record: SessionRecord) -> None:
+ self._record = record
+
+ async def get_session(
+ self,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ ) -> SessionRecord | None:
+ """Return the seeded record, or None for any other id."""
+ _ = user_id, agent_id
+ return self._record if session_id == self._record.id else None
+
+
+def _make_session(cwd: str | None = None) -> SessionRecord:
+ """Build a session record anchored at ``cwd``."""
+ return SessionRecord(
+ user_id="u",
+ agent_id="a",
+ id="s",
+ source=SessionSource.USER,
+ state=AgentState(),
+ config=SessionConfig(workspace_id="ws-1", name="t", cwd=cwd),
+ agent_snapshot=AgentRecord(
+ user_id="u",
+ source="user",
+ data=AgentData(
+ name="A",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ ),
+ ),
+ )
+
+
+class WorkspaceStatusTest(IsolatedAsyncioTestCase):
+ """Compose the response and degrade on every git failure mode."""
+
+ def setUp(self) -> None:
+ """Hold the backend so tests can assert on the calls it saw."""
+ self.backend = _FakeBackend()
+
+ async def _call(
+ self,
+ *results: Any,
+ cwd: str | None = None,
+ ) -> Any:
+ """Invoke the endpoint against a scripted backend."""
+ self.backend = _FakeBackend(*results)
+ workspace = _FakeWorkspace(self.backend)
+ return await get_workspace_status(
+ agent_id="a",
+ session_id="s",
+ user_id="u",
+ workspace_service=WorkspaceService(
+ _FakeStorage(_make_session(cwd)),
+ _FakeWorkspaceManager(workspace),
+ "secret",
+ ),
+ )
+
+ async def test_reports_branch_and_line_counts(self) -> None:
+ """Both commands succeeding yields a fully populated status."""
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=_STATUS_STDOUT, stderr=b""),
+ ExecResult(exit_code=0, stdout=_SHORTSTAT_STDOUT, stderr=b""),
+ )
+
+ self.assertEqual(result.workdir, "/workspace")
+ self.assertEqual(result.cwd, "/workspace")
+ self.assertIsNotNone(result.git)
+ self.assertEqual(result.git.branch, "main")
+ self.assertEqual(result.git.ahead, 2)
+ self.assertEqual(result.git.behind, 1)
+ self.assertEqual(result.git.unstaged, 1)
+ self.assertEqual(result.git.untracked, 1)
+ self.assertEqual(result.git.insertions, 15)
+ self.assertEqual(result.git.deletions, 20)
+
+ async def test_cwd_anchors_the_git_invocation(self) -> None:
+ """A relative cwd resolves against the workspace root.
+
+ Both commands must run there — reporting the root's branch while
+ the UI names a subdirectory would be quietly wrong.
+ """
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=_STATUS_STDOUT, stderr=b""),
+ ExecResult(exit_code=0, stdout=_SHORTSTAT_STDOUT, stderr=b""),
+ cwd="sub/project",
+ )
+
+ self.assertEqual(result.cwd, "/workspace/sub/project")
+ self.assertEqual(
+ [call_cwd for _, call_cwd in self.backend.calls],
+ ["/workspace/sub/project", "/workspace/sub/project"],
+ )
+
+ async def test_absolute_cwd_is_used_verbatim(self) -> None:
+ """A cwd outside the workspace root is honoured, not clamped."""
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=_STATUS_STDOUT, stderr=b""),
+ ExecResult(exit_code=0, stdout=_SHORTSTAT_STDOUT, stderr=b""),
+ cwd="/elsewhere/repo",
+ )
+
+ self.assertEqual(result.cwd, "/elsewhere/repo")
+
+ async def test_not_a_repository(self) -> None:
+ """Exit 128 is the ordinary "no repo here" answer."""
+ result = await self._call(
+ ExecResult(
+ exit_code=128,
+ stdout=b"",
+ stderr=b"fatal: not a git repository",
+ ),
+ )
+
+ self.assertIsNone(result.git)
+ self.assertEqual(result.workdir, "/workspace")
+
+ async def test_git_binary_missing(self) -> None:
+ """Exit 127 covers both a missing binary and a bad cwd."""
+ result = await self._call(
+ ExecResult(exit_code=127, stdout=b"", stderr=b"No such file"),
+ )
+
+ self.assertIsNone(result.git)
+
+ async def test_timeout(self) -> None:
+ """A timed-out command reports -1 rather than raising."""
+ result = await self._call(
+ ExecResult(exit_code=-1, stdout=b"", stderr=b"timed out"),
+ )
+
+ self.assertIsNone(result.git)
+
+ async def test_backend_raises(self) -> None:
+ """Docker and K8s raise transport errors out of ``exec_shell``.
+
+ Every other backend converts failures into a result, so this is
+ the path that would 500 without an explicit guard.
+ """
+ result = await self._call(RuntimeError("container is gone"))
+
+ self.assertIsNone(result.git)
+ self.assertEqual(result.cwd, "/workspace")
+
+ async def test_shortstat_failure_keeps_the_branch(self) -> None:
+ """An unborn HEAD breaks ``diff`` but not ``status``.
+
+ Running the two separately is what lets the branch survive; the
+ line counts fall back to zero.
+ """
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=_STATUS_STDOUT, stderr=b""),
+ ExecResult(
+ exit_code=128,
+ stdout=b"",
+ stderr=b"fatal: bad revision 'HEAD'",
+ ),
+ )
+
+ self.assertIsNotNone(result.git)
+ self.assertEqual(result.git.branch, "main")
+ self.assertEqual(result.git.insertions, 0)
+ self.assertEqual(result.git.deletions, 0)
+
+ async def test_shortstat_raises_keeps_the_branch(self) -> None:
+ """Same, when the second call raises instead of exiting."""
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=_STATUS_STDOUT, stderr=b""),
+ RuntimeError("connection reset"),
+ )
+
+ self.assertIsNotNone(result.git)
+ self.assertEqual(result.git.branch, "main")
+
+ async def test_unparseable_output_reports_nothing(self) -> None:
+ """Exiting zero is not enough — the output has to name a branch.
+
+ Real git always gives one or a commit, so neither means we are
+ not reading git, and a badge with no branch on it would be
+ worse than no badge.
+ """
+ result = await self._call(
+ ExecResult(exit_code=0, stdout=b"something else\0", stderr=b""),
+ )
+
+ self.assertIsNone(result.git)
+
+ async def test_missing_session_raises_404(self) -> None:
+ """An unknown session is a client error, not an empty status."""
+ with self.assertRaises(HTTPException) as ctx:
+ await get_workspace_status(
+ agent_id="a",
+ session_id="does-not-exist",
+ user_id="u",
+ workspace_service=WorkspaceService(
+ _FakeStorage(_make_session()),
+ _FakeWorkspaceManager(_FakeWorkspace(_FakeBackend())),
+ "secret",
+ ),
+ )
+
+ self.assertEqual(ctx.exception.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/tests/session_config_patch_test.py b/tests/session_config_patch_test.py
new file mode 100644
index 000000000..92a1799a1
--- /dev/null
+++ b/tests/session_config_patch_test.py
@@ -0,0 +1,304 @@
+# -*- coding: utf-8 -*-
+"""``PATCH /sessions/{id}`` test case — write isolation and cwd storage.
+
+The endpoint has to keep two writers apart. Configuration is written by
+this handler; ``AgentState`` is written by the chat run's ``_persist()``,
+which completes while the run still holds the session lock. Two rules
+follow, and both are asserted here:
+
+- a config change is refused while the lock is held, and
+- a config change that does not carry ``permission_mode`` must not send
+ ``state`` to storage at all, so the handler's opening snapshot can
+ never land on top of what the run has persisted since.
+"""
+import tempfile
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+import fakeredis.aioredis
+from fastapi.testclient import TestClient
+
+from agentscope.agent import ContextConfig, ReActConfig
+from agentscope.app import create_app
+from agentscope.app.message_bus import MessageBusKeys, RedisMessageBus
+from agentscope.app.storage import AgentData, AgentRecord, RedisStorage
+from agentscope.app.workspace_manager import LocalWorkspaceManager
+from agentscope.permission import PermissionMode
+from agentscope.message import UserMsg
+from agentscope.state import Task
+from agentscope.state._state import ReadCacheEntry
+
+HEADERS = {"X-User-ID": "alice"}
+
+
+class SessionConfigPatchTest(IsolatedAsyncioTestCase):
+ """Exercise the PATCH endpoint against a fakeredis-backed app."""
+
+ async def asyncSetUp(self) -> None:
+ """Start an app and seed one agent with one session."""
+ # enterContext binds the context manager to the test's lifetime;
+ # pylint does not recognise the unittest-native helper.
+ # pylint: disable=consider-using-with
+ workdir = self.enterContext(tempfile.TemporaryDirectory())
+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+
+ # Record every ``state`` argument storage receives, so a test can
+ # assert on what the handler chose to write rather than on what
+ # survived the round trip.
+ recorded_states: list[Any] = []
+
+ class _Storage(RedisStorage):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ async def upsert_session(self, *args: Any, **kwargs: Any) -> Any:
+ recorded_states.append(kwargs.get("state"))
+ return await super().upsert_session(*args, **kwargs)
+
+ class _Bus(RedisMessageBus):
+ async def __aenter__(self) -> Any:
+ self._client = redis
+ return self
+
+ async def aclose(self) -> None:
+ self._client = None
+
+ self.recorded_states = recorded_states
+ self.bus = _Bus()
+ app = create_app(
+ storage=_Storage(),
+ message_bus=self.bus,
+ workspace_manager=LocalWorkspaceManager(workdir),
+ enable_index_worker=False,
+ )
+ self.client = self.enterContext(TestClient(app))
+
+ storage = app.state.storage
+ self.agent_id = await storage.upsert_agent(
+ "alice",
+ AgentRecord(
+ user_id="alice",
+ data=AgentData(
+ name="ann",
+ system_prompt="You are ann.",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ ),
+ ),
+ )
+ created = self.client.post(
+ "/sessions/",
+ headers=HEADERS,
+ json={"agent_id": self.agent_id, "name": "before"},
+ )
+ self.assertEqual(created.status_code, 201)
+ self.session_id = created.json()["session_id"]
+
+ # Give the stored state something distinguishable, so a
+ # clobbering write is visible rather than merely theoretical.
+ self.storage = storage
+ record = await storage.get_session(
+ "alice",
+ self.agent_id,
+ self.session_id,
+ )
+ record.state.tasks_context.tasks = [
+ Task(
+ subject="written by the run",
+ description="",
+ metadata={},
+ id="1",
+ ),
+ ]
+ # The heavy fields, so trimming them is observable rather than
+ # vacuously true against a freshly created session.
+ record.state.context = [
+ UserMsg(name="alice", content="a long conversation"),
+ ]
+ record.state.summary = "a compressed history"
+ record.state.tool_context.read_file_cache = [
+ ReadCacheEntry(
+ lines=["file contents"],
+ updated_at=0.0,
+ bytes=13,
+ file_path="/w/a.py",
+ ),
+ ]
+ await storage.update_session_state(
+ user_id="alice",
+ agent_id=self.agent_id,
+ session_id=self.session_id,
+ state=record.state,
+ )
+ self.recorded_states.clear()
+
+ def _patch(self, body: dict) -> Any:
+ """Send a PATCH for the seeded session."""
+ return self.client.patch(
+ f"/sessions/{self.session_id}",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ json=body,
+ )
+
+ def test_config_only_patch_does_not_write_state(self) -> None:
+ """A rename leaves ``state`` entirely out of the storage call."""
+ response = self._patch({"name": "after"})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["config"]["name"], "after")
+ # The load-bearing assertion: not merely "state came back
+ # unchanged" (it would, since upsert re-reads) but "the handler
+ # never offered a state to write".
+ self.assertEqual(self.recorded_states, [None])
+
+ def test_permission_mode_patch_writes_only_that_field(self) -> None:
+ """``permission_mode`` is the one field that must carry state."""
+ response = self._patch({"permission_mode": "accept_edits"})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(self.recorded_states), 1)
+ written = self.recorded_states[0]
+ self.assertIsNotNone(written)
+ self.assertEqual(
+ written.permission_context.mode,
+ PermissionMode.ACCEPT_EDITS,
+ )
+ # Everything else in the state rides along untouched.
+ self.assertEqual(
+ [task.subject for task in written.tasks_context.tasks],
+ ["written by the run"],
+ )
+
+ async def test_patch_rejected_while_the_session_runs(self) -> None:
+ """Holding the run lock makes configuration read-only."""
+ lock_key = MessageBusKeys.session_lock(self.session_id)
+ async with self.bus.acquire_lock(lock_key, ttl_secs=30):
+ response = self._patch({"name": "after"})
+
+ self.assertEqual(response.status_code, 409)
+ self.assertIn("running", response.json()["detail"])
+ # Nothing reached storage, so the rejection is real and not just
+ # a status code applied after the fact.
+ self.assertEqual(self.recorded_states, [])
+
+ async def test_missing_session_reports_404_not_409(self) -> None:
+ """A missing session reports as missing even while locked.
+
+ The lock key is derived from the requested id, so a caller that
+ typos a session id would otherwise get a confusing 409 for a
+ session that never existed.
+ """
+ lock_key = MessageBusKeys.session_lock("ghost")
+ async with self.bus.acquire_lock(lock_key, ttl_secs=30):
+ response = self.client.patch(
+ "/sessions/ghost",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ json={"name": "after"},
+ )
+
+ self.assertEqual(response.status_code, 404)
+
+ def test_listing_strips_the_bulk_of_state(self) -> None:
+ """The list ships panel seeds, never the conversation.
+
+ ``context`` and ``tool_context`` hold the model's transcript and
+ the contents of every file it has read, so returning them would
+ make listing twenty sessions cost twenty transcripts to render a
+ sidebar that shows a name and a date.
+ """
+ listed = self.client.get(
+ "/sessions/",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ ).json()["sessions"][0]
+
+ state = listed["session"]["state"]
+ self.assertEqual(state["context"], [])
+ self.assertEqual(state["summary"], "")
+ self.assertEqual(state["tool_context"]["read_file_cache"], [])
+ # The two the UI actually seeds from must survive the trim.
+ self.assertEqual(
+ [task["subject"] for task in state["tasks_context"]["tasks"]],
+ ["written by the run"],
+ )
+ self.assertIn("mode", state["permission_context"])
+
+ def _listed(self) -> Any:
+ """Fetch the seeded session's entry from the list endpoint."""
+ return self.client.get(
+ "/sessions/",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ ).json()["sessions"][0]
+
+ def test_idle_session_reports_idle(self) -> None:
+ """A session nobody is running reports ``idle``."""
+ listed = self._listed()
+
+ self.assertEqual(listed["status"], "idle")
+ self.assertFalse(listed["is_running"])
+
+ async def test_running_session_reports_running(self) -> None:
+ """Holding the run lease is what makes a session ``running``."""
+ lock_key = MessageBusKeys.session_lock(self.session_id)
+ async with self.bus.acquire_lock(lock_key, ttl_secs=30):
+ listed = self._listed()
+
+ self.assertEqual(listed["status"], "running")
+ self.assertTrue(listed["is_running"])
+
+ def test_cwd_round_trips(self) -> None:
+ """A relative cwd is stored and read back verbatim."""
+ self.assertEqual(
+ self._patch({"cwd": "src/agentscope"}).status_code,
+ 200,
+ )
+
+ listed = self.client.get(
+ "/sessions/",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ ).json()
+ self.assertEqual(
+ listed["sessions"][0]["session"]["config"]["cwd"],
+ "src/agentscope",
+ )
+
+ def test_cwd_defaults_to_none_and_clears_to_none(self) -> None:
+ """``None`` means the workspace root, both initially and after."""
+ record = self.client.get(
+ "/sessions/",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ ).json()["sessions"][0]["session"]
+ self.assertIsNone(record["config"]["cwd"])
+
+ self._patch({"cwd": "src"})
+ self.assertEqual(self._patch({"cwd": None}).status_code, 200)
+
+ listed = self.client.get(
+ "/sessions/",
+ headers=HEADERS,
+ params={"agent_id": self.agent_id},
+ ).json()
+ self.assertIsNone(listed["sessions"][0]["session"]["config"]["cwd"])
+
+ def test_cwd_is_not_confined_to_the_workspace_root(self) -> None:
+ """Absolute paths and ``..`` are ordinary values, not attacks.
+
+ ``cwd`` only names a place to look — it never changes where a
+ tool executes — and the directory listing it feeds is itself
+ unconfined. Rejecting these would stop a user from pointing the
+ UI at a checkout that lives outside the workspace.
+ """
+ for outside in ("/etc", "..", "../elsewhere", "a/../../elsewhere"):
+ with self.subTest(cwd=outside):
+ response = self._patch({"cwd": outside})
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["config"]["cwd"], outside)
diff --git a/tests/workspace_skill_archive_test.py b/tests/workspace_skill_archive_test.py
index 3febb5ace..c26df571d 100644
--- a/tests/workspace_skill_archive_test.py
+++ b/tests/workspace_skill_archive_test.py
@@ -10,11 +10,10 @@ from unittest.async_case import IsolatedAsyncioTestCase
from fastapi import UploadFile
-from agentscope.app._service._skill_upload import (
+from agentscope.app._service import WorkspaceService
+from agentscope.app._service._workspace import (
SkillUploadError,
UploadManifest,
- _tar_stream,
- _validate_manifest,
)
from agentscope.workspace import LocalWorkspace
from agentscope.workspace._base import WorkspaceBase
@@ -222,25 +221,28 @@ class UploadManifestTest(IsolatedAsyncioTestCase):
manifest = self._manifest(
{"pack/SKILL.md": b"x", "pack/lib/run.py": b"y"},
)
- self.assertEqual(_validate_manifest(manifest), "pack")
+ self.assertEqual(
+ WorkspaceService.validate_manifest(manifest, 2),
+ "pack",
+ )
def test_rejects_multiple_roots(self) -> None:
"""Files from two folders are not one skill."""
manifest = self._manifest({"a/SKILL.md": b"x", "b/run.py": b"y"})
with self.assertRaises(SkillUploadError):
- _validate_manifest(manifest)
+ WorkspaceService.validate_manifest(manifest, 2)
def test_rejects_traversal(self) -> None:
"""A ``..`` segment is refused before anything is read."""
manifest = self._manifest({"pack/../../SKILL.md": b"x"})
with self.assertRaises(SkillUploadError):
- _validate_manifest(manifest)
+ WorkspaceService.validate_manifest(manifest, 1)
def test_rejects_missing_skill_md(self) -> None:
"""The root must hold a SKILL.md."""
manifest = self._manifest({"pack/readme.md": b"x"})
with self.assertRaises(SkillUploadError):
- _validate_manifest(manifest)
+ WorkspaceService.validate_manifest(manifest, 1)
def test_rejects_oversized_file(self) -> None:
"""A single part over the per-file limit is refused."""
@@ -253,7 +255,19 @@ class UploadManifestTest(IsolatedAsyncioTestCase):
},
)
with self.assertRaises(SkillUploadError):
- _validate_manifest(manifest)
+ WorkspaceService.validate_manifest(manifest, 2)
+
+ def test_rejects_part_count_mismatch(self) -> None:
+ """A manifest that does not describe the parts sent is refused.
+
+ The tar headers come from the manifest, so a mismatch would
+ pair one file's size with another's bytes.
+ """
+ manifest = self._manifest(
+ {"pack/SKILL.md": b"x", "pack/lib/run.py": b"y"},
+ )
+ with self.assertRaises(SkillUploadError):
+ WorkspaceService.validate_manifest(manifest, 1)
async def test_stream_round_trips(self) -> None:
"""The emitted tar reads back with the same members."""
@@ -264,7 +278,10 @@ class UploadManifestTest(IsolatedAsyncioTestCase):
manifest = self._manifest(files)
chunks = [
chunk
- async for chunk in _tar_stream(manifest, self._uploads(files))
+ async for chunk in WorkspaceService.tar_stream(
+ manifest,
+ self._uploads(files),
+ )
]
archive = tarfile.open(fileobj=io.BytesIO(b"".join(chunks)))
@@ -283,5 +300,5 @@ class UploadManifestTest(IsolatedAsyncioTestCase):
)
uploads = self._uploads({"pack/SKILL.md": b"much longer"})
with self.assertRaises(SkillUploadError):
- async for _ in _tar_stream(manifest, uploads):
+ async for _ in WorkspaceService.tar_stream(manifest, uploads):
pass