Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(workspaces): add scoped instructions and refine learning UI

Bingxi Zhao (Frank)3cbecb247942
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index 287827a4d..fb2260d8a 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -7,6 +7,12 @@ labels:
consult_subagent: "Consult agent"
final_response: "Final response"
+workspace_instructions_policy: |-
+ The user configured the following preferences for this workspace. Apply them to teaching,
+ collaboration and presentation, including in this capability. They take precedence over
+ generic style defaults; an explicit request in the current task can adjust these preferences.
+ Continue to follow the capability's required workflow, output protocol and tool permissions.
+
general: |-
You are DeepTutor, an interactive tutor and learning companion.
Never describe internal stages, prompt blocks, or implementation details
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index 99c737084..16a9f170f 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -7,6 +7,11 @@ labels:
consult_subagent: "咨询智能体"
final_response: "生成回答"
+workspace_instructions_policy: |-
+ 以下是用户为当前工作区设置的偏好。将它们应用到教学、协作和表达方式,包括当前能力。
+ 这些偏好优先于通用风格默认值;当前任务中的明确要求可以调整这些偏好。
+ 继续遵守当前能力必需的工作流程、输出协议和工具权限。
+
general: |-
你是 DeepTutor,一名互动式学习教练和学习伙伴。
除非用户明确询问系统设计,否则不要描述内部阶段、提示词块或实现细节。
diff --git a/deeptutor/agents/loop/context_budget.py b/deeptutor/agents/loop/context_budget.py
index c9de8cd7e..eafa991f1 100644
--- a/deeptutor/agents/loop/context_budget.py
+++ b/deeptutor/agents/loop/context_budget.py
@@ -50,6 +50,7 @@ _BLOCK_SEGMENTS: dict[str, str] = {
"extended_tools": "extended_tools",
"notebooks": "notebooks",
"workspace": "workspace",
+ "workspace_instructions": "workspace_instructions",
}
_CAPABILITY_SEGMENT = "capability"
diff --git a/deeptutor/agents/loop/prompt_blocks.py b/deeptutor/agents/loop/prompt_blocks.py
index 5bd5ba256..7d5107882 100644
--- a/deeptutor/agents/loop/prompt_blocks.py
+++ b/deeptutor/agents/loop/prompt_blocks.py
@@ -141,6 +141,13 @@ class LoopPromptAssembler:
# Capability playbooks sit high so they frame the whole turn when active;
# empty blocks are omitted by ``system_prompt``'s join.
blocks.extend(capability_blocks or [])
+ workspace = context.runtime.workspace
+ if workspace is not None and workspace.instructions.strip():
+ policy = self._t("workspace_instructions_policy")
+ instructions = workspace.instructions.strip()
+ if policy:
+ instructions = f"{policy}\n\n{instructions}"
+ blocks.append(PromptBlock("workspace_instructions", instructions))
if context.sidebar_context:
blocks.append(PromptBlock("sidebar_tutor_context", context.sidebar_context))
# A conversation that belongs to a course carries that course's
diff --git a/deeptutor/api/routers/workspace.py b/deeptutor/api/routers/workspace.py
index 67f50a7ad..f0c3717b8 100644
--- a/deeptutor/api/routers/workspace.py
+++ b/deeptutor/api/routers/workspace.py
@@ -19,6 +19,7 @@ from deeptutor.services.workspace import (
WorkspaceItem,
get_content_workspace_service,
)
+from deeptutor.services.workspace.models import MAX_WORKSPACE_INSTRUCTIONS_CHARS
from deeptutor.services.workspace.resources import WorkspaceResources
settings_router = APIRouter()
@@ -30,12 +31,14 @@ class WorkspacePathPayload(BaseModel):
class CreateWorkspacePayload(BaseModel):
+ instructions: str | None = Field(default=None, max_length=MAX_WORKSPACE_INSTRUCTIONS_CHARS)
resources: WorkspaceResources | None = None
name: str = Field(min_length=1, max_length=100)
path: str | None = None
class UpdateWorkspacePayload(BaseModel):
+ instructions: str | None = Field(default=None, max_length=MAX_WORKSPACE_INSTRUCTIONS_CHARS)
resources: WorkspaceResources | None = None
name: str | None = Field(default=None, min_length=1, max_length=100)
archived: bool | None = None
@@ -246,6 +249,7 @@ async def create_workspace(payload: CreateWorkspacePayload) -> dict:
payload.name,
payload.path,
resources=payload.resources.model_dump() if payload.resources else None,
+ instructions=payload.instructions,
)
except WorkspaceError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -258,11 +262,12 @@ async def update_registered_workspace(workspace_id: str, payload: UpdateWorkspac
from deeptutor.services.workspace.activity import data_activity
from deeptutor.services.workspace.data_migration import assert_no_pending_recovery
- with data_activity(exclusive=True):
+ # Instruction edits are atomic metadata updates. A running turn owns
+ # its admitted snapshot, so these edits can coexist with its data lease.
+ changes = payload.model_dump(exclude_unset=True)
+ with data_activity(exclusive=set(changes) != {"instructions"}):
assert_no_pending_recovery(reject_unreadable=True)
- workspace = get_content_workspace_service().update_workspace(
- workspace_id, **payload.model_dump(exclude_unset=True)
- )
+ workspace = get_content_workspace_service().update_workspace(workspace_id, **changes)
except WorkspaceError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"workspace": workspace}
diff --git a/deeptutor/core/context.py b/deeptutor/core/context.py
index b97701633..313e54621 100644
--- a/deeptutor/core/context.py
+++ b/deeptutor/core/context.py
@@ -44,6 +44,7 @@ class WorkspaceRuntimeContext:
output_dir: str = ""
logical_output_dir: str = "outputs"
security_level: str = "off"
+ instructions: str = ""
@dataclass
diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.py
index 2cacdb7ec..ee04f4b93 100644
--- a/deeptutor/services/session/turns/executor.py
+++ b/deeptutor/services/session/turns/executor.py
@@ -938,6 +938,7 @@ class TurnExecutor:
session_id=session_id,
turn_id=turn_id,
workspace_id=payload.get("_content_workspace_id"),
+ instructions=payload.get("_workspace_instructions"),
),
),
metadata={
diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py
index 1124a8fca..064758e72 100644
--- a/deeptutor/services/session/turns/request_preparer.py
+++ b/deeptutor/services/session/turns/request_preparer.py
@@ -232,6 +232,9 @@ class TurnRequestPreparer:
else workspace_service.session_binding(session["id"])
)
payload["_content_workspace_id"] = binding.workspace_id
+ payload["_workspace_instructions"] = workspace_service.workspace_instructions(
+ binding.workspace_id
+ )
legacy_watching = (
payload.get("workspace_mode") == "immersive_watching"
@@ -686,6 +689,9 @@ class TurnRequestPreparer:
else workspace_service.session_binding(parent_session_id)
)
payload["_content_workspace_id"] = inherited_binding.workspace_id
+ payload["_workspace_instructions"] = workspace_service.workspace_instructions(
+ inherited_binding.workspace_id
+ )
preference_update.update(
{
"parent_session_id": parent_session_id,
diff --git a/deeptutor/services/workspace/catalog.py b/deeptutor/services/workspace/catalog.py
index 2fca501b5..24a13e311 100644
--- a/deeptutor/services/workspace/catalog.py
+++ b/deeptutor/services/workspace/catalog.py
@@ -21,7 +21,11 @@ from typing import TYPE_CHECKING, Any
import uuid
from deeptutor.multi_user.context import get_current_user
-from deeptutor.services.workspace.models import WorkspaceBinding, WorkspaceError
+from deeptutor.services.workspace.models import (
+ MAX_WORKSPACE_INSTRUCTIONS_CHARS,
+ WorkspaceBinding,
+ WorkspaceError,
+)
from deeptutor.utils.secret_files import ensure_private_directory
logger = logging.getLogger(__name__)
@@ -289,6 +293,7 @@ class WorkspaceCatalogMixin:
"created_at": row["created_at"],
"status": status["status"],
"error": status.get("error", ""),
+ "instructions": row.get("instructions") or "",
"resources": row.get("resources")
or {"skills": None, "mcp": None, "knowledge_bases": None},
}
@@ -296,12 +301,19 @@ class WorkspaceCatalogMixin:
return sorted(result, key=lambda row: {"system": 0, "general": 1}.get(row["kind"], 2))
def create_workspace(
- self, name: str, path: str | None = None, *, resources: dict | None = None
+ self,
+ name: str,
+ path: str | None = None,
+ *,
+ resources: dict | None = None,
+ instructions: str | None = None,
) -> dict[str, Any]:
self.assert_available()
name = name.strip()
if not name or len(name) > 100:
raise WorkspaceError("A workspace name must contain 1 to 100 characters.")
+ if instructions is not None:
+ instructions = self._validate_instructions(instructions)
if resources is not None:
from deeptutor.services.workspace.resources import validate_resources
@@ -318,7 +330,11 @@ class WorkspaceCatalogMixin:
for row in self.list_workspaces():
if Path(row["path"]).resolve() == root:
return self.update_workspace(
- row["workspace_id"], name=name, archived=False, resources=resources
+ row["workspace_id"],
+ name=name,
+ archived=False,
+ resources=resources,
+ instructions=instructions,
)
binding = WorkspaceBinding(workspace_id, root, name)
self._ensure_ready(binding)
@@ -333,6 +349,7 @@ class WorkspaceCatalogMixin:
"archived": False,
"created_at": _utc_now(),
"resources": resources or {},
+ "instructions": instructions or "",
}
)
if saved["kind"] != "workspace":
@@ -348,10 +365,13 @@ class WorkspaceCatalogMixin:
name: str | None = None,
archived: bool | None = None,
resources: dict | None = None,
+ instructions: str | None = None,
) -> dict[str, Any]:
self.assert_available()
if name is not None and (not name.strip() or len(name.strip()) > 100):
raise WorkspaceError("A workspace name must contain 1 to 100 characters.")
+ if instructions is not None:
+ instructions = self._validate_instructions(instructions)
if resources is not None:
from deeptutor.services.workspace.resources import validate_resources
@@ -375,6 +395,8 @@ class WorkspaceCatalogMixin:
raise WorkspaceError("The default workspace cannot be renamed or archived.")
if resources is not None:
row["resources"] = resources
+ if instructions is not None:
+ row["instructions"] = instructions
if name is not None:
row["display_name"] = name.strip()
if archived is not None:
@@ -385,6 +407,28 @@ class WorkspaceCatalogMixin:
)
return next(row for row in self.list_workspaces() if row["workspace_id"] == workspace_id)
+ @staticmethod
+ def _validate_instructions(instructions: str) -> str:
+ if (
+ not isinstance(instructions, str)
+ or len(instructions) > MAX_WORKSPACE_INSTRUCTIONS_CHARS
+ ):
+ raise WorkspaceError(
+ f"Workspace instructions must be text of at most {MAX_WORKSPACE_INSTRUCTIONS_CHARS} characters."
+ )
+ return instructions.strip()
+
+ def workspace_instructions(self, workspace_id: str | None = None) -> str:
+ """Read owner-scoped preferences; legacy and private bindings default to empty."""
+ if workspace_id is None:
+ workspace_id = self.current_binding().workspace_id
+ elif not workspace_id:
+ workspace_id = self._builtin_id("general")
+ row = next((r for r in self._catalog() if r["workspace_id"] == workspace_id), None)
+ if row is None or row.get("kind") not in {"workspace", "general"}:
+ return ""
+ return str(row.get("instructions") or "")
+
def validate_chat_binding(
self, workspace_id: str, *, existing: bool = False
) -> WorkspaceBinding:
diff --git a/deeptutor/services/workspace/models.py b/deeptutor/services/workspace/models.py
index 65c1b4c35..e5a2ba75a 100644
--- a/deeptutor/services/workspace/models.py
+++ b/deeptutor/services/workspace/models.py
@@ -6,6 +6,8 @@ from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
+MAX_WORKSPACE_INSTRUCTIONS_CHARS = 10_000
+
class WorkspaceError(ValueError):
"""A workspace path, binding, or operation is not allowed."""
diff --git a/deeptutor/services/workspace/service.py b/deeptutor/services/workspace/service.py
index 6b0635a83..570b81212 100644
--- a/deeptutor/services/workspace/service.py
+++ b/deeptutor/services/workspace/service.py
@@ -302,6 +302,7 @@ class ContentWorkspaceService(WorkspaceCatalogMixin):
session_id: str,
turn_id: str,
workspace_id: str | None = None,
+ instructions: str | None = None,
) -> WorkspaceRuntimeContext:
self.assert_available()
binding = (
@@ -330,6 +331,11 @@ class ContentWorkspaceService(WorkspaceCatalogMixin):
output_dir=str(output),
logical_output_dir=logical,
security_level=self.security_level(),
+ instructions=(
+ self.workspace_instructions(binding.workspace_id)
+ if instructions is None
+ else instructions
+ ),
)
def resolve(
diff --git a/docs-for-user/workspaces.md b/docs-for-user/workspaces.md
index c58fa82f1..7ce6fa973 100644
--- a/docs-for-user/workspaces.md
+++ b/docs-for-user/workspaces.md
@@ -26,6 +26,12 @@
已有普通对话可以移动到另一个工作区,关联子对话、附件和产物一起移动。有学习资料或其他会话依赖时,使用数据迁移预览完整关联内容。运行中的会话不能移动。归档保留内容并阻止新写入,恢复后可继续学习。
+## 工作区提示词
+
+在「设置 → 工作区」新建工作区时填写提示词,或点击已有工作区的「工作区提示词」编辑。默认工作区也可以设置。可填写学习目标、已有基础、教学方式和回答偏好,最多 10,000 字符;清空并保存后恢复默认行为。
+
+提示词自动应用于该工作区内的对话、解题、主动提问、引导学习、沉浸式阅读、课程学习和常规可视化。每轮开始时固定当前内容,编辑从下一轮生效。Deep Research、出题和 Manim 动画流程暂不使用这部分提示词。
+
## Partner 绑定工作区
新建 Partner 的「资料库」步骤可以选择已有工作区,配置页也可以更改绑定。绑定后持续共享该工作区的文件、知识库、技能和笔记本,生成文件写入该工作区的 `outputs/`;工作区的资源分配规则和 Partner 的工具开关同时生效。Soul、对话记录和 Partner 记忆保持独立。更改绑定从下一条消息开始生效。
diff --git a/tests/agents/chat/test_context_budget.py b/tests/agents/chat/test_context_budget.py
index b4314c767..00f1ce60c 100644
--- a/tests/agents/chat/test_context_budget.py
+++ b/tests/agents/chat/test_context_budget.py
@@ -128,6 +128,14 @@ def test_learning_journal_is_not_folded_into_capability() -> None:
assert _tokens(budget) == {"learning_journal": _chars(f"## learning_journal\n{snapshot}")}
+def test_workspace_instructions_have_their_own_context_budget_segment() -> None:
+ content = "Explain with geometric intuition"
+ budget = _budget(blocks=[PromptBlock("workspace_instructions", content)])
+ assert _tokens(budget) == {
+ "workspace_instructions": _chars(f"## workspace_instructions\n{content}")
+ }
+
+
def test_segments_sorted_desc_with_empty_ones_dropped() -> None:
budget = _budget(
blocks=[
diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py
index 8fe60d3ad..a429e08bb 100644
--- a/tests/agents/chat/test_language_prompts.py
+++ b/tests/agents/chat/test_language_prompts.py
@@ -7,7 +7,7 @@ import pytest
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.agents.loop.prompt_blocks import ChatPromptAssembler
from deeptutor.capabilities.mastery.pipeline import MasteryLoopPipeline
-from deeptutor.core.context import UnifiedContext
+from deeptutor.core.context import TurnRuntimeContext, UnifiedContext, WorkspaceRuntimeContext
from deeptutor.runtime.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
@@ -162,3 +162,37 @@ def test_prompt_blocks_include_localized_optional_context() -> None:
system_prompt = assembler.render(blocks)
assert "## sidebar_tutor_context" in system_prompt
assert "把代码和静态数据加载进内存" in system_prompt
+
+
[email protected]("language", ["en", "zh"])
+ "mode",
+ [
+ "chat",
+ "deep_solve",
+ "ask_questions",
+ "immersive_reading",
+ "course_study",
+ "visualize",
+ "mastery_path",
+ ],
+)
+def test_workspace_instructions_reach_shared_loop_prompts_and_stay_in_the_system(language, mode):
+ pipeline_type = MasteryLoopPipeline if mode == "mastery_path" else AgenticChatPipeline
+ pipeline = pipeline_type(language=language)
+ text = "先讲直觉。Keep {literal braces} and line breaks.\nThen show examples."
+ context = UnifiedContext(
+ active_capability=mode,
+ runtime=TurnRuntimeContext(workspace=WorkspaceRuntimeContext(instructions=text)),
+ )
+ prompt = pipeline._build_system_prompt([], context)
+ assert prompt.count("## workspace_instructions\n") == 1
+ assert text in prompt
+ assert "workspace_instructions" not in pipeline._runtime_snapshots
+ assert (
+ "当前能力必需的工作流程" in prompt
+ if language == "zh"
+ else "capability's required workflow" in prompt
+ )
+ context.runtime.workspace = WorkspaceRuntimeContext()
+ assert "## workspace_instructions\n" not in pipeline._build_system_prompt([], context)
diff --git a/tests/api/test_workspace_router.py b/tests/api/test_workspace_router.py
index a70b82b95..74fa87f53 100644
--- a/tests/api/test_workspace_router.py
+++ b/tests/api/test_workspace_router.py
@@ -64,6 +64,60 @@ def test_workspace_settings_select_and_reset(workspace_api, tmp_path: Path) -> N
assert reset.json()["is_default"] is True
+def test_workspace_instructions_create_update_clear_and_validate(workspace_api):
+ client, service = workspace_api
+ endpoint = "/api/settings/workspace/registrations"
+ created = client.post(
+ endpoint, json={"name": "Algebra", "instructions": "Start with intuition"}
+ )
+ assert created.status_code == 200
+ row = created.json()["workspace"]
+ assert row["instructions"] == "Start with intuition"
+ url = f"{endpoint}/{row['workspace_id']}"
+ assert (
+ client.patch(url, json={"name": "Linear algebra"}).json()["workspace"]["instructions"]
+ == row["instructions"]
+ )
+ assert (
+ client.patch(url, json={"instructions": "Use examples"}).json()["workspace"]["instructions"]
+ == "Use examples"
+ )
+ assert client.patch(url, json={"instructions": ""}).json()["workspace"]["instructions"] == ""
+ assert client.patch(url, json={"instructions": "x" * 10001}).status_code == 422
+ assert (
+ client.post(endpoint, json={"name": "Invalid", "instructions": "x" * 10001}).status_code
+ == 422
+ )
+ general = service.general_binding().workspace_id
+ assert (
+ client.patch(
+ f"{endpoint}/{general}", json={"instructions": "Default preferences"}
+ ).status_code
+ == 200
+ )
+ assert service.workspace_instructions("") == "Default preferences"
+ assert (
+ client.patch(
+ f"{endpoint}/{service.system_binding().workspace_id}", json={"instructions": "Invalid"}
+ ).status_code
+ == 400
+ )
+
+
+def test_instruction_edits_can_be_saved_while_a_turn_holds_its_activity_lease(workspace_api):
+ from deeptutor.services.workspace.activity import data_activity
+
+ client, service = workspace_api
+ row = service.create_workspace("Algebra")
+ url = f"/api/settings/workspace/registrations/{row['workspace_id']}"
+ with data_activity():
+ saved = client.patch(url, json={"instructions": "Next-turn preferences"})
+ assert saved.status_code == 200
+ assert saved.json()["workspace"]["instructions"] == "Next-turn preferences"
+ # Destructive lifecycle changes still need the exclusive lease.
+ assert client.patch(url, json={"archived": True}).status_code == 400
+
+
def test_workspace_item_endpoint_serves_the_published_snapshot(workspace_api) -> None:
client, service = workspace_api
binding = service.current_binding(ensure_output=True)
diff --git a/tests/services/workspace/test_chat_workspaces.py b/tests/services/workspace/test_chat_workspaces.py
index 273d1886e..24c3f9a8f 100644
--- a/tests/services/workspace/test_chat_workspaces.py
+++ b/tests/services/workspace/test_chat_workspaces.py
@@ -109,17 +109,20 @@ async def test_admission_freezes_binding_and_resume_ignores_global_folder(
):
store = SQLiteSessionStore(tmp_path / "sessions.sqlite3")
runtime = TurnRuntimeManager(store)
- a = service.create_workspace("A")
- b = service.create_workspace("B")
+ a = service.create_workspace("A", instructions="Original teaching style")
+ b = service.create_workspace("B", instructions="Other teaching style")
captured = []
+ ready = asyncio.Event()
async def run(execution):
+ await ready.wait()
captured.append(
service.create_runtime_context(
capability=execution.capability,
session_id=execution.session_id,
turn_id=execution.turn_id,
workspace_id=execution.payload.get("_content_workspace_id"),
+ instructions=execution.payload.get("_workspace_instructions"),
)
)
await store.update_turn_status(execution.turn_id, "completed")
@@ -134,8 +137,11 @@ async def test_admission_freezes_binding_and_resume_ignores_global_folder(
}
)
service.set_workspace(b["path"])
+ service.update_workspace(a["workspace_id"], instructions="Updated teaching style")
+ ready.set()
await runtime._executions[turn["id"]].task
assert captured[-1].root == a["path"]
+ assert captured[-1].instructions == "Original teaching style"
saved = await store.get_session(session["id"])
assert saved["preferences"]["workspace_id"] == a["workspace_id"]
_, next_turn = await runtime.start_turn(
@@ -143,6 +149,7 @@ async def test_admission_freezes_binding_and_resume_ignores_global_folder(
)
await runtime._executions[next_turn["id"]].task
assert captured[-1].root == a["path"]
+ assert captured[-1].instructions == "Updated teaching style"
with pytest.raises(RuntimeError, match="workspace changed"):
await runtime.start_turn(
{
diff --git a/tests/services/workspace/test_instructions.py b/tests/services/workspace/test_instructions.py
new file mode 100644
index 000000000..e609980e1
--- /dev/null
+++ b/tests/services/workspace/test_instructions.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.multi_user.models import CurrentUser, UserScope
+from deeptutor.multi_user.paths import get_account_path_service, user_context
+from deeptutor.services.workspace import ContentWorkspaceService, WorkspaceError
+from deeptutor.services.workspace.models import MAX_WORKSPACE_INSTRUCTIONS_CHARS
+
+
+def service(tmp_path, monkeypatch):
+ monkeypatch.delenv("DEEPTUTOR_WORKSPACE_ROOT", raising=False)
+ owner = CurrentUser("instructions-test", "test", "admin", UserScope("admin", "test", tmp_path))
+ with user_context(owner):
+ get_account_path_service().ensure_all_directories()
+ yield ContentWorkspaceService()
+
+
+def test_instructions_are_isolated_persistent_and_optional_on_existing_rows(service):
+ a = service.create_workspace("A", instructions=" Explain intuitively.\nUse examples. ")
+ b = service.create_workspace("B")
+ general = service.general_binding().workspace_id
+ service.update_workspace(general, instructions="Default preferences")
+
+ assert a["instructions"] == "Explain intuitively.\nUse examples."
+ assert b["instructions"] == ""
+ assert ContentWorkspaceService().workspace_instructions(a["workspace_id"]) == a["instructions"]
+ assert service.workspace_instructions(b["workspace_id"]) == ""
+ assert service.workspace_instructions("") == "Default preferences"
+ service.update_workspace(a["workspace_id"], name="Renamed", resources={})
+ assert service.workspace_instructions(a["workspace_id"]) == a["instructions"]
+ assert service.create_workspace("Same folder", a["path"])["instructions"] == a["instructions"]
+ service.update_workspace(a["workspace_id"], instructions=" \n ")
+ assert service.workspace_instructions(a["workspace_id"]) == ""
+ # Built-ins/registrations created by earlier versions have no instructions field.
+ assert service.workspace_instructions(service.system_binding().workspace_id) == ""
+
+
+def test_instructions_follow_owner_scope_and_cannot_modify_system_workspace(service, tmp_path):
+ row = service.create_workspace("A", instructions="Private preferences")
+ other = CurrentUser("other", "other", "admin", UserScope("admin", "other", tmp_path / "other"))
+ with user_context(other):
+ assert service.workspace_instructions(row["workspace_id"]) == ""
+ with pytest.raises(WorkspaceError, match="not found"):
+ service.update_workspace(row["workspace_id"], instructions="Changed")
+ with pytest.raises(WorkspaceError, match="not found"):
+ service.update_workspace(service.system_binding().workspace_id, instructions="Changed")
+
+
+def test_runtime_instructions_are_frozen_and_survive_folder_migration(service, tmp_path):
+ row = service.create_workspace("A", instructions="Old preferences")
+ before = service.create_runtime_context(
+ capability="chat", session_id="s", turn_id="one", workspace_id=row["workspace_id"]
+ )
+ service.update_workspace(row["workspace_id"], instructions="New preferences")
+ after = service.create_runtime_context(
+ capability="deep_solve", session_id="s", turn_id="two", workspace_id=row["workspace_id"]
+ )
+ admitted = service.create_runtime_context(
+ capability="chat",
+ session_id="s",
+ turn_id="three",
+ workspace_id=row["workspace_id"],
+ instructions=before.instructions,
+ )
+ assert before.instructions == admitted.instructions == "Old preferences"
+ assert after.instructions == "New preferences"
+ service.migrate_workspace(row["workspace_id"], str(tmp_path / "moved"))
+ assert service.workspace_instructions(row["workspace_id"]) == "New preferences"
+
+
+def test_instruction_limit_is_enforced_without_overwriting_saved_preferences(service):
+ row = service.create_workspace("A", instructions="Saved")
+ oversized = "x" * (MAX_WORKSPACE_INSTRUCTIONS_CHARS + 1)
+ with pytest.raises(WorkspaceError, match="at most"):
+ service.update_workspace(row["workspace_id"], instructions=oversized)
+ with pytest.raises(WorkspaceError, match="at most"):
+ service.create_workspace("Invalid", instructions=oversized)
+ assert service.workspace_instructions(row["workspace_id"]) == "Saved"
diff --git a/web/app/globals.css b/web/app/globals.css
index 90221fc67..0c23a6d12 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -36,6 +36,7 @@
@container feature-page (min-width: 520px) {
.dt-page-grid-2,
.dt-page-grid-3,
+ .dt-page-grid-4,
.dt-page-grid-5 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@@ -64,6 +65,7 @@
}
@container feature-page (min-width: 1040px) {
+ .dt-page-grid-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.dt-page-grid-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
}
diff --git a/web/components/chat/home/ContextBudgetChip.tsx b/web/components/chat/home/ContextBudgetChip.tsx
index 543ce88c0..e88b64275 100644
--- a/web/components/chat/home/ContextBudgetChip.tsx
+++ b/web/components/chat/home/ContextBudgetChip.tsx
@@ -38,6 +38,7 @@ const SEGMENT_COLORS: Record<string, string> = {
sources: "#0891b2",
notebooks: "#e879a3",
workspace: "#65a30d",
+ workspace_instructions: "#0d9488",
capability: "#64748b",
};
diff --git a/web/components/layout/FeaturePage.tsx b/web/components/layout/FeaturePage.tsx
index c889d7923..3ac5cb1e1 100644
--- a/web/components/layout/FeaturePage.tsx
+++ b/web/components/layout/FeaturePage.tsx
@@ -103,6 +103,6 @@ export function pageActionClass(variant: 'primary' | 'secondary' = 'primary') {
/** Column limits describe the content, while one set of container breakpoints
* controls every library. Works on divs and semantic lists alike.
*/
-export function pageGridClass(columns: 2 | 3 | 5 | 'board' = 2) {
+export function pageGridClass(columns: 2 | 3 | 4 | 5 | 'board' = 2) {
return `dt-page-grid dt-page-grid-${columns}`
}
diff --git a/web/components/learning/LearningWays.tsx b/web/components/learning/LearningWays.tsx
index 4f186085f..bb672a249 100644
--- a/web/components/learning/LearningWays.tsx
+++ b/web/components/learning/LearningWays.tsx
@@ -38,62 +38,71 @@ export function LearningWays() {
<h2 id={id} className="sr-only">
{t('Ways to learn')}
</h2>
- <div className={pageGridClass(5)}>
- {LEARNING_SURFACES.map(surface => {
+ <div className={pageGridClass(4)}>
+ {LEARNING_SURFACES.map((surface, index) => {
const opened = openKind === surface.kind
return (
<motion.div
key={surface.kind}
- layoutId={sharedId('surface', surface.kind)}
- className="group relative h-full border border-border bg-card shadow-sm transition-colors hover:border-primary/30"
- style={{ borderRadius: 20 }}
- whileHover={reduceMotion || opened ? undefined : { y: -3 }}
- whileTap={reduceMotion || opened ? undefined : { scale: 0.985, y: -1 }}
- transition={spring}
+ initial={reduceMotion ? false : { opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: reduceMotion ? 0 : 0.24, delay: reduceMotion ? 0 : index * 0.04 }}
>
- <button
- type="button"
- onClick={event => {
- triggerRef.current = event.currentTarget
- setOpenKind(surface.kind)
- }}
- aria-haspopup="dialog"
- aria-expanded={opened}
- aria-controls={opened ? `${id}-panel` : undefined}
- className="relative flex h-full min-h-[196px] w-full flex-col items-start rounded-[20px] p-5 text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring"
+ {/* Entry staggering stays outside the card-to-dialog projection
+ so opening and returning never inherit an entrance delay. */}
+ <motion.div
+ layoutId={sharedId('surface', surface.kind)}
+ className="group relative h-full border border-border bg-card shadow-sm transition-colors hover:border-primary/30"
+ style={{ borderRadius: 20 }}
+ animate={{ y: 0, scale: 1 }}
+ whileHover={reduceMotion || opened ? undefined : { y: -2 }}
+ whileTap={reduceMotion || opened ? undefined : { scale: 0.99, y: 0 }}
+ transition={{ layout: spring, duration: reduceMotion ? 0 : 0.16 }}
>
- <span className="mb-5 flex w-full items-center justify-between">
- <motion.span
+ <button
+ type="button"
+ onClick={event => {
+ triggerRef.current = event.currentTarget
+ setOpenKind(surface.kind)
+ }}
+ aria-haspopup="dialog"
+ aria-expanded={opened}
+ aria-controls={opened ? `${id}-panel` : undefined}
+ className="relative flex h-full min-h-[196px] w-full flex-col items-start rounded-[20px] p-5 text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring"
+ >
+ <span className="mb-5 flex w-full items-center justify-between">
+ <motion.span
+ layout="position"
+ layoutId={sharedId('icon', surface.kind)}
+ transition={spring}
+ className={tileClass(surface.accent)}
+ >
+ <surface.icon size={21} aria-hidden="true" />
+ </motion.span>
+ <ArrowUpRight
+ size={18}
+ aria-hidden="true"
+ className="text-muted-foreground/50 transition duration-200 group-hover:-translate-y-0.5 group-hover:translate-x-0.5 group-hover:text-foreground group-focus-within:text-foreground motion-reduce:transform-none"
+ />
+ </span>
+ <motion.h3
layout="position"
- layoutId={sharedId('icon', surface.kind)}
+ layoutId={sharedId('title', surface.kind)}
transition={spring}
- className={tileClass(surface.accent)}
+ className={titleClass}
>
- <surface.icon size={21} aria-hidden="true" />
- </motion.span>
- <ArrowUpRight
- size={18}
- aria-hidden="true"
- className="text-muted-foreground/50 transition duration-200 group-hover:-translate-y-0.5 group-hover:translate-x-0.5 group-hover:text-foreground group-focus-within:text-foreground motion-reduce:transform-none"
- />
- </span>
- <motion.h3
- layout="position"
- layoutId={sharedId('title', surface.kind)}
- transition={spring}
- className={titleClass}
- >
- {t(surface.title)}
- </motion.h3>
- <motion.p
- layout="position"
- layoutId={sharedId('description', surface.kind)}
- transition={spring}
- className="mt-2 text-[12.5px] leading-[1.7] text-muted-foreground"
- >
- {t(surface.description)}
- </motion.p>
- </button>
+ {t(surface.title)}
+ </motion.h3>
+ <motion.p
+ layout="position"
+ layoutId={sharedId('description', surface.kind)}
+ transition={spring}
+ className="mt-2 text-[12.5px] leading-[1.7] text-muted-foreground"
+ >
+ {t(surface.description)}
+ </motion.p>
+ </button>
+ </motion.div>
</motion.div>
)
})}
diff --git a/web/components/workspaces/WorkspaceInstructionsField.tsx b/web/components/workspaces/WorkspaceInstructionsField.tsx
new file mode 100644
index 000000000..3704f1672
--- /dev/null
+++ b/web/components/workspaces/WorkspaceInstructionsField.tsx
@@ -0,0 +1,59 @@
+'use client'
+
+import { useId } from 'react'
+import { useTranslation } from 'react-i18next'
+import { inputClass } from '@/components/settings/shared'
+
+export function WorkspaceInstructionsField({
+ value,
+ onChange,
+}: {
+ value: string
+ onChange: (value: string) => void
+}) {
+ const { t } = useTranslation()
+ const id = useId()
+ return (
+ <div className="space-y-2">
+ <label htmlFor={id} className="block text-sm font-medium">
+ {t('Workspace instructions')}
+ </label>
+ <p
+ id={`${id}-description`}
+ className="text-xs leading-relaxed text-[var(--muted-foreground)]"
+ >
+ {t(
+ 'Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.'
+ )}
+ </p>
+ <textarea
+ id={id}
+ aria-describedby={`${id}-description ${id}-scope`}
+ className={`${inputClass} min-h-36 resize-y leading-relaxed`}
+ value={value}
+ onChange={event => onChange(event.target.value)}
+ maxLength={10000}
+ rows={6}
+ placeholder={t(
+ 'For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.'
+ )}
+ />
+ <p id={`${id}-scope`} className="text-xs leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ 'Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.'
+ )}
+ </p>
+ <div className="flex items-center justify-between gap-3 text-xs text-[var(--muted-foreground)]">
+ <button
+ type="button"
+ onClick={() => onChange('')}
+ disabled={!value}
+ className="underline underline-offset-2 disabled:opacity-50"
+ >
+ {t('Clear instructions')}
+ </button>
+ <span>{t('{{used}} / {{limit}} characters', { used: value.length, limit: 10000 })}</span>
+ </div>
+ </div>
+ )
+}
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index ed1073d60..1c2d25e92 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -12409,6 +12409,8 @@ export interface components {
};
/** CreateWorkspacePayload */
readonly CreateWorkspacePayload: {
+ /** Instructions */
+ readonly instructions?: string | null;
/** Name */
readonly name: string;
/** Path */
@@ -16622,6 +16624,8 @@ export interface components {
readonly UpdateWorkspacePayload: {
/** Archived */
readonly archived?: boolean | null;
+ /** Instructions */
+ readonly instructions?: string | null;
/** Name */
readonly name?: string | null;
readonly resources?: components["schemas"]["WorkspaceResources"] | null;
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index 7a514cd92..e371c204d 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -2849,6 +2849,18 @@
},
"CreateWorkspacePayload": {
"properties": {
+ "instructions": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Instructions"
+ },
"name": {
"maxLength": 100,
"minLength": 1,
@@ -12257,6 +12269,18 @@
],
"title": "Archived"
},
+ "instructions": {
+ "anyOf": [
+ {
+ "maxLength": 10000,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Instructions"
+ },
"name": {
"anyOf": [
{
diff --git a/web/features/settings/sections/WorkspaceSettingsSection.tsx b/web/features/settings/sections/WorkspaceSettingsSection.tsx
index bf798693d..5d1dbe5b4 100644
--- a/web/features/settings/sections/WorkspaceSettingsSection.tsx
+++ b/web/features/settings/sections/WorkspaceSettingsSection.tsx
@@ -3,10 +3,11 @@
import Tooltip from "@/shared/ui/Tooltip";
import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
-import { Archive, ArchiveRestore, Folder, FolderInput, Globe2, Pencil, Plus, Settings2 } from 'lucide-react'
+import { Archive, ArchiveRestore, FileText, Folder, FolderInput, Globe2, Pencil, Plus, Settings2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { SettingSection, SettingsPageHeader, inputClass, subPanelClass } from '@/components/settings/shared'
import { WorkspaceResourcePicker } from '@/components/workspaces/WorkspaceResourcePicker'
+import { WorkspaceInstructionsField } from '@/components/workspaces/WorkspaceInstructionsField'
import { SystemWorkspaceSnapshot } from '@/components/workspaces/SystemWorkspaceSnapshot'
import {
getWorkspaceCatalog, saveWorkspace, migrateWorkspace, workspaceChatHref, inheritedWorkspaceResources,
@@ -20,6 +21,8 @@ const primaryClass = 'inline-flex items-center justify-center gap-1.5 rounded-lg
function WorkspaceRow({ row, run, busy }: { row: ChatWorkspaceRegistration; run: RunAction; busy: boolean }) {
const { t } = useTranslation()
const [resourcesOpen, setResourcesOpen] = useState(false)
+ const [instructionsOpen, setInstructionsOpen] = useState(false)
+ const [instructions, setInstructions] = useState(row.instructions ?? '')
const [resources, setResources] = useState(row.resources ?? inheritedWorkspaceResources())
const [editing, setEditing] = useState(false)
const [name, setName] = useState(row.display_name)
@@ -34,13 +37,14 @@ function WorkspaceRow({ row, run, busy }: { row: ChatWorkspaceRegistration; run:
<Icon size={18} strokeWidth={1.6} className="shrink-0 text-[var(--muted-foreground)]" />
<h3 className="min-w-0 flex-1 break-words text-[14px] font-medium">{label}</h3>
{row.archived && <span className="text-xs text-[var(--muted-foreground)]">{t('Archived')}</span>}
- <div className="flex items-center gap-0.5 sm:opacity-0 sm:transition-opacity sm:group-hover:opacity-100 sm:group-focus-within:opacity-100">
+ <div className="flex max-w-full flex-wrap items-center gap-0.5 sm:opacity-0 sm:transition-opacity sm:group-hover:opacity-100 sm:group-focus-within:opacity-100">
{row.kind !== 'system' && !row.archived && row.status === 'ready' && !busy && (
<Link className={actionClass} href={row.kind === 'general' ? '/chat?dt_workspace=' : workspaceChatHref(row.workspace_id)}>
<Plus size={14} />{t('New chat')}
</Link>
)}
{row.kind !== 'system' && !row.archived && <button type="button" className={actionClass} onClick={() => { setResources(row.resources ?? inheritedWorkspaceResources()); setResourcesOpen(!resourcesOpen) }}><Settings2 size={14} />{t('Assigned resources')}</button>}
+ {row.kind !== 'system' && !row.archived && <button type="button" className={actionClass} aria-expanded={instructionsOpen} onClick={() => { setInstructions(row.instructions ?? ''); setInstructionsOpen(!instructionsOpen) }}><FileText size={14} />{t('Workspace instructions')}</button>}
{custom && <Tooltip label={t('Rename workspace')} side="top">
<button type="button" className={actionClass} aria-label={t('Rename workspace')} onClick={() => { setName(row.display_name); setEditing(!editing); setMoving(false) }}><Pencil size={14} /></button>
</Tooltip>}
@@ -56,6 +60,12 @@ function WorkspaceRow({ row, run, busy }: { row: ChatWorkspaceRegistration; run:
{!custom && <p className="mb-2 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{row.kind === 'system' ? t('Sanitized configuration snapshots, Skill files and MCP inventory. API keys and tokens remain in private configuration.') : t('Conversations without a selected workspace share files in this folder.')}</p>}
<p className="select-all break-all font-mono text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">{row.path}</p>
{row.archived && <p className="mt-1 text-xs text-[var(--muted-foreground)]">{t('Archived. Existing conversations and files are kept.')}</p>}
+ {instructionsOpen && (
+ <form className={`${subPanelClass} mt-3 space-y-3 p-4`} onSubmit={async event => { event.preventDefault(); if (await run(() => saveWorkspace({ instructions }, row.workspace_id))) setInstructionsOpen(false) }}>
+ <WorkspaceInstructionsField value={instructions} onChange={setInstructions} />
+ <div className="flex gap-2"><button type="submit" className={primaryClass}>{t('Save')}</button><button type="button" className={actionClass} onClick={() => setInstructionsOpen(false)}>{t('Cancel')}</button></div>
+ </form>
+ )}
{resourcesOpen && (
<form className={`${subPanelClass} mt-3 space-y-3 p-4`} onSubmit={async event => { event.preventDefault(); if (await run(() => saveWorkspace({ resources }, row.workspace_id))) setResourcesOpen(false) }}>
<WorkspaceResourcePicker value={resources} onChange={setResources} workspaceId={row.workspace_id} />
@@ -92,6 +102,7 @@ export default function WorkspaceSettingsSection() {
const [busy, setBusy] = useState(false)
const [creating, setCreating] = useState(false)
const [resources, setResources] = useState(inheritedWorkspaceResources)
+ const [instructions, setInstructions] = useState('')
const [name, setName] = useState('')
const [path, setPath] = useState('')
const [error, setError] = useState('')
@@ -130,11 +141,12 @@ export default function WorkspaceSettingsSection() {
{creating && (
<form className={`${subPanelClass} my-4 space-y-3 p-4 sm:p-5`} onSubmit={async event => {
event.preventDefault()
- if (await run(() => saveWorkspace({ name: name.trim(), resources, ...(path.trim() ? { path: path.trim() } : {}) }))) { setName(''); setPath(''); setResources(inheritedWorkspaceResources()); setCreating(false) }
+ if (await run(() => saveWorkspace({ name: name.trim(), resources, ...(instructions.trim() ? { instructions } : {}), ...(path.trim() ? { path: path.trim() } : {}) }))) { setName(''); setPath(''); setInstructions(''); setResources(inheritedWorkspaceResources()); setCreating(false) }
}}>
<label className="block text-sm">{t('Workspace name')}<input autoFocus className={`${inputClass} mt-1`} value={name} onChange={event => setName(event.target.value)} required maxLength={100} placeholder={t('e.g. Probability')} /></label>
<label className="block text-sm">{t('Existing folder path (optional)')}<input className={`${inputClass} mt-1 font-mono`} value={path} onChange={event => setPath(event.target.value)} placeholder={t('Leave empty to create under root')} /></label>
<p className="text-xs leading-relaxed text-[var(--muted-foreground)]">{t('Place files in the folder for the agent to read. Generated files go into outputs/.')}</p>
+ <WorkspaceInstructionsField value={instructions} onChange={setInstructions} />
<WorkspaceResourcePicker value={resources} onChange={setResources} />
<div className="flex gap-2"><button type="submit" disabled={!name.trim()} className={primaryClass}>{t('Create workspace')}</button><button type="button" className={actionClass} onClick={() => setCreating(false)}>{t('Cancel')}</button></div>
</form>
diff --git a/web/lib/use-auto-sized-textarea.ts b/web/lib/use-auto-sized-textarea.ts
index f2a64e113..10b5a49df 100644
--- a/web/lib/use-auto-sized-textarea.ts
+++ b/web/lib/use-auto-sized-textarea.ts
@@ -11,7 +11,7 @@
* a stale clipped value — that was the source of the prior shrink bug.
*/
-import { useLayoutEffect, type RefObject } from "react";
+import { useCallback, useLayoutEffect, type RefObject } from "react";
export interface AutoSizedTextareaOptions {
/** Minimum height in pixels (clamps ``scrollHeight`` from below). */
@@ -25,13 +25,38 @@ export function useAutoSizedTextarea(
value: string,
{ min = 0, max = Number.POSITIVE_INFINITY }: AutoSizedTextareaOptions = {},
): void {
- useLayoutEffect(() => {
+ const resize = useCallback(() => {
const el = ref.current;
if (!el) return;
+ // scrollHeight includes wrapped placeholder text in an empty textarea.
+ // A narrow/entering reading sidebar must not turn that hint into a tall
+ // empty composer. Measure the input itself, then restore the hint.
+ const placeholder = el.placeholder;
+ if (!el.value) el.placeholder = "";
el.style.height = "auto";
const natural = el.scrollHeight;
+ if (!el.value) el.placeholder = placeholder;
const bounded = Math.min(Math.max(natural, min), max);
el.style.height = `${bounded}px`;
el.style.overflowY = natural > max ? "auto" : "hidden";
- }, [ref, value, min, max]);
+ }, [ref, min, max]);
+
+ useLayoutEffect(resize, [resize, value]);
+
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ let previousWidth: number | undefined;
+ const observer = new ResizeObserver(([entry]) => {
+ if (!entry) return;
+ const width = entry.contentRect.width;
+ // Ignore height notifications caused by our own measurement, but keep
+ // track of hidden panels so reopening at the same width remeasures.
+ if (width === previousWidth) return;
+ previousWidth = width;
+ if (width > 0) resize();
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [ref, resize]);
}
diff --git a/web/lib/workspaces-api.ts b/web/lib/workspaces-api.ts
index 00436ada6..cfe368e7c 100644
--- a/web/lib/workspaces-api.ts
+++ b/web/lib/workspaces-api.ts
@@ -31,6 +31,7 @@ export function getWorkspaceResources(workspaceId = ''): Promise<WorkspaceResour
}
export interface ChatWorkspaceRegistration {
+ instructions?: string
resources?: WorkspaceResources
workspace_id: string
kind: 'system' | 'general' | 'workspace'
@@ -64,7 +65,7 @@ export function listWorkspaces(force = false): Promise<ChatWorkspaceRegistration
}
export async function saveWorkspace(
- input: { name?: string; path?: string; archived?: boolean; resources?: WorkspaceResources },
+ input: { name?: string; path?: string; archived?: boolean; resources?: WorkspaceResources; instructions?: string },
workspaceId?: string
): Promise<ChatWorkspaceRegistration> {
const result = await request<{ workspace: ChatWorkspaceRegistration }>(
diff --git a/web/locales/de/app.json b/web/locales/de/app.json
index 27b30fee7..d5fac6c89 100644
--- a/web/locales/de/app.json
+++ b/web/locales/de/app.json
@@ -5505,5 +5505,12 @@
"No durable indexing run recorded yet.": "Noch kein dauerhafter Indexierungslauf aufgezeichnet.",
"Approve this MCP origin for private-network connections": "Diesen MCP-Ursprung für private Netzwerkverbindungen freigeben",
"Use an administrator-approved private MCP origin": "Einen administrativ freigegebenen privaten MCP-Ursprung verwenden",
- "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Nur dieses Schema, dieser Host und Port dürfen private Docker- oder LAN-Adressen verwenden. Metadatenadressen bleiben gesperrt."
+ "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Nur dieses Schema, dieser Host und Port dürfen private Docker- oder LAN-Adressen verwenden. Metadatenadressen bleiben gesperrt.",
+ "Workspace instructions": "Arbeitsbereichsanweisungen",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Lege Lernziele, Lehrstil und Antwortpräferenzen für diesen Arbeitsbereich fest. Leer lassen, um das Standardverhalten zu verwenden.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "Beispiel: Ich lerne lineare Algebra. Erkläre zuerst die geometrische Intuition, dann die Formeln, und gib Hinweise vor vollständigen Lösungen.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Gilt für Chat, Problemlösung, Rückfragen, geführtes Lernen, Lesen, Kurslernen und Standardvisualisierungen. Änderungen gelten ab der nächsten Runde.",
+ "Clear instructions": "Anweisungen leeren",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} Zeichen",
+ "contextBudget.segment.workspace_instructions": "Arbeitsbereichsanweisungen"
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index edc3fc29e..ccc6056b8 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -5505,5 +5505,12 @@
"No durable indexing run recorded yet.": "No durable indexing run recorded yet.",
"Approve this MCP origin for private-network connections": "Approve this MCP origin for private-network connections",
"Use an administrator-approved private MCP origin": "Use an administrator-approved private MCP origin",
- "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked."
+ "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.",
+ "Workspace instructions": "Workspace instructions",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.",
+ "Clear instructions": "Clear instructions",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} characters",
+ "contextBudget.segment.workspace_instructions": "Workspace instructions"
}
diff --git a/web/locales/en/common.json b/web/locales/en/common.json
index acf6e72cc..ceb4128d6 100644
--- a/web/locales/en/common.json
+++ b/web/locales/en/common.json
@@ -35,5 +35,11 @@
"admin": "admin",
"Account library": "Account library",
"{{count}} resources selected_one": "{{count}} resource selected",
- "{{count}} resources selected_other": "{{count}} resources selected"
+ "{{count}} resources selected_other": "{{count}} resources selected",
+ "Workspace instructions": "Workspace instructions",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.",
+ "Clear instructions": "Clear instructions",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} characters"
}
diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json
index 86e801fc1..29ff4e9f4 100644
--- a/web/locales/fr/app.json
+++ b/web/locales/fr/app.json
@@ -5885,5 +5885,12 @@
"settings.providerServices.customDescription": "L’URL doit implémenter l’API choisie. Ajoutez ensuite les identifiants et les autres types de services avec leurs adaptateurs.",
"settings.providerServices.addHint": "Les étiquettes indiquent les intégrations, pas les autorisations du compte. Une connexion peut servir plusieurs types de modèles ; les comptes et produits peuvent rester séparés.",
"settings.providerServices.catalogListed": "Liste des modèles obtenue. Testez un modèle pour vérifier l’accès à l’inférence.",
- "settings.providerServices.partial": "Seule une partie de la liste a été obtenue. Les types manquants restent inconnus et peuvent être ajoutés manuellement."
+ "settings.providerServices.partial": "Seule une partie de la liste a été obtenue. Les types manquants restent inconnus et peuvent être ajoutés manuellement.",
+ "Workspace instructions": "Instructions de l’espace de travail",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Définissez les objectifs d’apprentissage, le style pédagogique et les préférences de réponse de cet espace. Laissez vide pour utiliser le comportement par défaut.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "Exemple : j’apprends l’algèbre linéaire. Expliquez l’intuition géométrique avant les formules et donnez des indices avant les solutions complètes.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "S’applique au chat, à la résolution, aux questions, à l’apprentissage guidé, à la lecture, aux cours et aux visualisations standard. Les changements prennent effet au prochain tour.",
+ "Clear instructions": "Effacer les instructions",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} caractères",
+ "contextBudget.segment.workspace_instructions": "Instructions de l’espace de travail"
}
diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json
index b00c5b116..43806081a 100644
--- a/web/locales/pl/app.json
+++ b/web/locales/pl/app.json
@@ -5521,5 +5521,12 @@
"No durable indexing run recorded yet.": "Nie zapisano jeszcze trwałego zadania indeksowania.",
"Approve this MCP origin for private-network connections": "Zatwierdź ten origin MCP dla połączeń w sieci prywatnej",
"Use an administrator-approved private MCP origin": "Użyj prywatnego originu MCP zatwierdzonego przez administratora",
- "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Tylko ten schemat, host i port mogą korzystać z prywatnych adresów Docker lub LAN. Adresy metadanych pozostają zablokowane."
+ "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Tylko ten schemat, host i port mogą korzystać z prywatnych adresów Docker lub LAN. Adresy metadanych pozostają zablokowane.",
+ "Workspace instructions": "Instrukcje obszaru roboczego",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Ustaw cele nauki, styl nauczania i preferencje odpowiedzi dla tego obszaru. Pozostaw puste, aby używać domyślnego zachowania.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "Na przykład: uczę się algebry liniowej. Wyjaśniaj intuicję geometryczną przed wzorami i dawaj wskazówki przed pełnymi rozwiązaniami.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Dotyczy czatu, rozwiązywania, pytań, nauki z przewodnikiem, czytania, kursów i standardowych wizualizacji. Zmiany obowiązują od następnej tury.",
+ "Clear instructions": "Wyczyść instrukcje",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} znaków",
+ "contextBudget.segment.workspace_instructions": "Instrukcje obszaru roboczego"
}
diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json
index 7893f7dad..a75d39e50 100644
--- a/web/locales/uk/app.json
+++ b/web/locales/uk/app.json
@@ -5521,5 +5521,12 @@
"No durable indexing run recorded yet.": "Збереженого запису про запуск індексації поки немає.",
"Approve this MCP origin for private-network connections": "Схвалити це джерело MCP для з'єднань із приватною мережею",
"Use an administrator-approved private MCP origin": "Використовувати приватне джерело MCP, схвалене адміністратором",
- "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Лише ця схема, хост і порт можуть використовувати приватні адреси Docker або локальної мережі. Адреси метаданих залишаються заблокованими."
+ "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "Лише ця схема, хост і порт можуть використовувати приватні адреси Docker або локальної мережі. Адреси метаданих залишаються заблокованими.",
+ "Workspace instructions": "Інструкції робочого простору",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "Укажіть навчальні цілі, стиль викладання та вподобання щодо відповідей для цього робочого простору. Залиште порожнім для стандартної поведінки.",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "Наприклад: я вивчаю лінійну алгебру. Спочатку пояснюйте геометричну інтуїцію, потім формули; давайте підказки перед повними розв’язаннями.",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "Застосовується до чату, розв’язування, запитань, керованого навчання, читання, курсів і стандартних візуалізацій. Зміни діють із наступного ходу.",
+ "Clear instructions": "Очистити інструкції",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} символів",
+ "contextBudget.segment.workspace_instructions": "Інструкції робочого простору"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index efff7abf1..ab2861866 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -5505,5 +5505,12 @@
"No durable indexing run recorded yet.": "尚未记录持久索引任务。",
"Approve this MCP origin for private-network connections": "批准此 MCP 来源使用私有网络连接",
"Use an administrator-approved private MCP origin": "使用管理员批准的私有 MCP 来源",
- "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "仅此协议、主机和端口可使用私有 Docker 或局域网地址。元数据地址仍被阻止。"
+ "Only this scheme, host and port can use private Docker or LAN addresses. Metadata addresses remain blocked.": "仅此协议、主机和端口可使用私有 Docker 或局域网地址。元数据地址仍被阻止。",
+ "Workspace instructions": "工作区提示词",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "设置这个工作区的学习目标、教学方式和回答偏好。留空时使用默认行为。",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "例如:我正在学习线性代数。先解释几何直觉,再引入公式;先给提示,再给完整解答。",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "适用于对话、解题、主动提问、引导学习、沉浸式阅读、课程学习和常规可视化。从下一轮开始生效。",
+ "Clear instructions": "清空提示词",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} 字符",
+ "contextBudget.segment.workspace_instructions": "工作区提示词"
}
diff --git a/web/locales/zh/common.json b/web/locales/zh/common.json
index 7155b75ad..8d9f3963e 100644
--- a/web/locales/zh/common.json
+++ b/web/locales/zh/common.json
@@ -35,5 +35,11 @@
"admin": "管理员分配",
"Account library": "账户资源库",
"{{count}} resources selected_one": "已选择 {{count}} 项资源",
- "{{count}} resources selected_other": "已选择 {{count}} 项资源"
+ "{{count}} resources selected_other": "已选择 {{count}} 项资源",
+ "Workspace instructions": "工作区提示词",
+ "Set learning goals, teaching style and response preferences for this workspace. Leave blank to use the default behavior.": "设置这个工作区的学习目标、教学方式和回答偏好。留空时使用默认行为。",
+ "For example: I am learning linear algebra. Explain the geometric intuition before introducing formulas, and give hints before complete solutions.": "例如:我正在学习线性代数。先解释几何直觉,再引入公式;先给提示,再给完整解答。",
+ "Applies to Chat, Solve, Ask Questions, Guided Learning, Reading, Course Study and standard visualizations. Changes take effect on the next turn.": "适用于对话、解题、主动提问、引导学习、沉浸式阅读、课程学习和常规可视化。从下一轮开始生效。",
+ "Clear instructions": "清空提示词",
+ "{{used}} / {{limit}} characters": "{{used}} / {{limit}} 字符"
}
diff --git a/web/tests/use-auto-sized-textarea.spec.tsx b/web/tests/use-auto-sized-textarea.spec.tsx
new file mode 100644
index 000000000..f0fe93109
--- /dev/null
+++ b/web/tests/use-auto-sized-textarea.spec.tsx
@@ -0,0 +1,85 @@
+import { useRef } from "react";
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
+
+let notifyResize: ResizeObserverCallback;
+const disconnect = vi.fn();
+let contentHeight = 26;
+
+function Input({ value = "", min = 28 }: { value?: string; min?: number }) {
+ const ref = useRef<HTMLTextAreaElement>(null);
+ useAutoSizedTextarea(ref, value, { min, max: 200 });
+ return <textarea ref={ref} value={value} readOnly rows={1} placeholder="Ask about this material…" />;
+}
+
+function resize(width: number) {
+ act(() => notifyResize(
+ [{ contentRect: { width } } as ResizeObserverEntry],
+ {} as ResizeObserver,
+ ));
+}
+
+beforeEach(() => {
+ contentHeight = 26;
+ disconnect.mockClear();
+ vi.stubGlobal("ResizeObserver", class {
+ constructor(callback: ResizeObserverCallback) { notifyResize = callback; }
+ observe() {}
+ disconnect = disconnect;
+ });
+ vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(function (this: HTMLElement) {
+ const field = this as HTMLTextAreaElement;
+ // Browsers include a wrapping placeholder even when the value is empty.
+ return !field.value && field.placeholder ? 520 : contentHeight;
+ });
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+it("keeps an empty field compact without losing its placeholder", () => {
+ const { rerender } = render(<Input />);
+ const input = screen.getByRole("textbox");
+ expect(input).toHaveStyle({ height: "28px", overflowY: "hidden" });
+ expect(input).toHaveAttribute("placeholder", "Ask about this material…");
+ rerender(<Input min={64} />);
+ expect(input).toHaveStyle({ height: "64px" });
+});
+
+it("caps long input and shrinks again after sending or deleting it", () => {
+ contentHeight = 520;
+ const { rerender } = render(<Input value={"line\n".repeat(20)} />);
+ const input = screen.getByRole("textbox");
+ expect(input).toHaveStyle({ height: "200px", overflowY: "auto" });
+ contentHeight = 26;
+ rerender(<Input />);
+ expect(input).toHaveStyle({ height: "28px", overflowY: "hidden" });
+});
+
+it("remeasures wrapping when a sidebar changes width, but ignores height-only notifications", () => {
+ contentHeight = 156;
+ const { unmount } = render(<Input value="A question that wraps in a narrow sidebar" />);
+ const input = screen.getByRole("textbox");
+ resize(150);
+ expect(input).toHaveStyle({ height: "156px" });
+ contentHeight = 52;
+ resize(400);
+ expect(input).toHaveStyle({ height: "52px" });
+ const measured = vi.spyOn(HTMLElement.prototype, "scrollHeight", "get");
+ measured.mockClear();
+ resize(400);
+ expect(measured).not.toHaveBeenCalled();
+ unmount();
+ expect(disconnect).toHaveBeenCalledOnce();
+});
+
+it("remeasures after a hidden panel reopens at the same width", () => {
+ const { rerender } = render(<Input value="Question" />);
+ resize(400);
+ resize(0);
+ contentHeight = 0;
+ rerender(<Input value={"Question\n".repeat(8)} />);
+ contentHeight = 208;
+ resize(400);
+ expect(screen.getByRole("textbox")).toHaveStyle({ height: "200px", overflowY: "auto" });
+});
diff --git a/web/tests/workspace-i18n.spec.ts b/web/tests/workspace-i18n.spec.ts
index 3e3d9b67b..e084ee988 100644
--- a/web/tests/workspace-i18n.spec.ts
+++ b/web/tests/workspace-i18n.spec.ts
@@ -11,5 +11,8 @@ it('loads all workspace resource translations in the runtime namespace', async (
}
expect(t('Assigned resources')).toBe('分配资源')
expect(t('MCP services')).toBe('MCP 服务')
+ expect(t('Workspace instructions')).toBe('工作区提示词')
+ expect(t('Clear instructions')).toBe('清空提示词')
+ expect(t('contextBudget.segment.workspace_instructions')).toBe('工作区提示词')
expect(t('{{count}} resources selected', { count: 2 })).toBe('已选择 2 项资源')
})
diff --git a/web/tests/workspace-instructions.spec.tsx b/web/tests/workspace-instructions.spec.tsx
new file mode 100644
index 000000000..3a8a0b40d
--- /dev/null
+++ b/web/tests/workspace-instructions.spec.tsx
@@ -0,0 +1,119 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import WorkspaceSettingsSection from '@/features/settings/sections/WorkspaceSettingsSection'
+
+const fixture = vi.hoisted(() => ({ catalog: vi.fn(), save: vi.fn() }))
+vi.mock('@/lib/workspaces-api', async original => ({
+ ...(await original<object>()),
+ getWorkspaceCatalog: fixture.catalog,
+ saveWorkspace: fixture.save,
+}))
+vi.mock('@/components/workspaces/WorkspaceResourcePicker', () => ({
+ WorkspaceResourcePicker: () => null,
+}))
+vi.mock('@/components/workspaces/SystemWorkspaceSnapshot', () => ({
+ SystemWorkspaceSnapshot: () => null,
+}))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
+afterEach(cleanup)
+beforeEach(() => {
+ vi.clearAllMocks()
+ fixture.save.mockResolvedValue({})
+ fixture.catalog.mockResolvedValue({
+ root: '/workspaces',
+ workspaces: [
+ {
+ workspace_id: 'system',
+ display_name: 'System',
+ kind: 'system',
+ path: '/system',
+ status: 'ready',
+ },
+ {
+ workspace_id: 'default',
+ display_name: 'Default',
+ kind: 'general',
+ path: '/default',
+ status: 'ready',
+ instructions: 'Default style',
+ },
+ {
+ workspace_id: 'algebra',
+ display_name: 'Algebra',
+ kind: 'workspace',
+ path: '/algebra',
+ status: 'ready',
+ instructions: 'Start with intuition',
+ },
+ {
+ workspace_id: 'archived',
+ display_name: 'Archived',
+ kind: 'workspace',
+ path: '/archived',
+ archived: true,
+ status: 'ready',
+ },
+ ],
+ })
+})
+
+it('edits only the selected workspace and keeps drafts when saving fails', async () => {
+ render(<WorkspaceSettingsSection />)
+ const row = within(await screen.findByRole('article', { name: 'Algebra' }))
+ fireEvent.click(row.getByRole('button', { name: 'Workspace instructions' }))
+ const editor = row.getByRole('textbox', { name: 'Workspace instructions' })
+ expect(editor).toHaveValue('Start with intuition')
+ expect(editor).toHaveAttribute('maxlength', '10000')
+ fireEvent.change(editor, { target: { value: 'Give hints first' } })
+ fixture.save.mockRejectedValueOnce(new Error('Could not save'))
+ fireEvent.click(row.getByRole('button', { name: 'Save' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not save')
+ expect(editor).toHaveValue('Give hints first')
+ expect(fixture.save).toHaveBeenCalledWith({ instructions: 'Give hints first' }, 'algebra')
+ fireEvent.click(row.getByRole('button', { name: 'Save' }))
+ await waitFor(() =>
+ expect(row.queryByRole('textbox', { name: 'Workspace instructions' })).toBeNull()
+ )
+})
+
+it('supports clearing the default workspace instructions and excludes system and archived editors', async () => {
+ render(<WorkspaceSettingsSection />)
+ const row = within(await screen.findByRole('article', { name: 'Default workspace' }))
+ fireEvent.click(row.getByRole('button', { name: 'Workspace instructions' }))
+ expect(row.getByRole('textbox', { name: 'Workspace instructions' })).toHaveValue('Default style')
+ fireEvent.click(row.getByRole('button', { name: 'Clear instructions' }))
+ expect(row.getByRole('textbox', { name: 'Workspace instructions' })).toHaveValue('')
+ fireEvent.click(row.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(fixture.save).toHaveBeenCalledWith({ instructions: '' }, 'default'))
+ expect(
+ within(screen.getByRole('article', { name: 'System workspace' })).queryByRole('button', {
+ name: 'Workspace instructions',
+ })
+ ).toBeNull()
+ expect(
+ within(screen.getByRole('article', { name: 'Archived' })).queryByRole('button', {
+ name: 'Workspace instructions',
+ })
+ ).toBeNull()
+})
+
+it('saves workspace instructions at creation and starts the next creation with an empty draft', async () => {
+ render(<WorkspaceSettingsSection />)
+ await screen.findByRole('article', { name: 'Algebra' })
+ fireEvent.click(screen.getByRole('button', { name: 'New workspace' }))
+ fireEvent.change(screen.getByRole('textbox', { name: 'Workspace name' }), {
+ target: { value: 'Physics' },
+ })
+ fireEvent.change(screen.getByRole('textbox', { name: 'Workspace instructions' }), {
+ target: { value: 'Explain using experiments' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Create workspace' }))
+ await waitFor(() =>
+ expect(fixture.save).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Physics', instructions: 'Explain using experiments' })
+ )
+ )
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Create workspace' })).toBeNull())
+ fireEvent.click(screen.getByRole('button', { name: 'New workspace' }))
+ expect(screen.getByRole('textbox', { name: 'Workspace instructions' })).toHaveValue('')
+})