Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(gallery): rename the fileManager node to gallery
trohitg81eb0fcb2f87
diff --git a/client/src/types/INodeProperties.ts b/client/src/types/INodeProperties.tsindex 2c3b3018..8d15b751 100644--- a/client/src/types/INodeProperties.ts+++ b/client/src/types/INodeProperties.ts@@ -208,8 +208,8 @@ export interface INodeUIHints {isTaskManagerPanel?: boolean;/** MiddleSection: render live managed-process inspection and controls. */isProcessManagerPanel?: boolean;- /** MiddleSection: render the workspace file browser (drag files to params). */- isFileManagerPanel?: boolean;+ /** MiddleSection: render the workspace gallery (drag files to params). */+ isGalleryPanel?: boolean;/** Special-case panel for gmaps_create with map preview. */showLocationPanel?: boolean;/** ConsolePanel: this node is a chat-message target. */diff --git a/server/nodes/filesystem/gallery/__init__.py b/server/nodes/filesystem/gallery/__init__.pynew file mode 100644index 00000000..7fc00870--- /dev/null+++ b/server/nodes/filesystem/gallery/__init__.py@@ -0,0 +1,194 @@+"""Gallery — browse the workflow's workspace from the editor.++The panel is the point: it lists what a workflow has actually produced and+lets a file be dragged straight onto another node's parameter. Before this,+using a produced file meant already knowing its path and typing it by hand.++Deliberately **not** ``usable_as_tool``. ``fsSearch`` (ls/glob/grep) and+``fileModify`` (write/edit) already cover what an agent needs, and this node+carries destructive operations — shipping an editor panel should not hand+every agent a delete tool as a side effect. If agent-facing delete is ever+wanted it belongs on ``fileModify``, where the tool description can be+written carefully.++Running the node is not a no-op: it emits the listing as ``FileRef`` rows so+downstream nodes consume workspace files inside a workflow, not just in the+editor.+"""++from __future__ import annotations++from typing import Any, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from ._service import WORKSPACE_LIST_DEFAULT, list_directory, list_matching, to_file_ref+++class GalleryParams(BaseModel):+ path: str = Field(+ default="",+ description="Workspace-relative directory to list. Empty = workspace root.",+ )+ pattern: str = Field(+ default="",+ description="Optional glob (e.g. '*.wav'). Set = recursive search under path.",+ )+ selection: List[str] = Field(+ default_factory=list,+ description="Specific workspace-relative files to emit, pinned in the panel.",+ )+ include_dirs: bool = Field(+ default=False,+ description="Include directories in the output as well as files.",+ )+ limit: int = Field(default=200, ge=1, le=1000)++ model_config = ConfigDict(extra="ignore")+++class GalleryOutput(BaseModel):+ path: Optional[str] = None+ files: Optional[list] = None # serialized FileRef rows+ directories: Optional[list] = None+ count: Optional[int] = None+ truncated: Optional[bool] = None+ missing: Optional[list] = None++ model_config = ConfigDict(extra="allow")+++class GalleryNode(ActionNode):+ type = "gallery"+ display_name = "Gallery"+ subtitle = "Workspace Files"+ group = ("filesystem",)+ description = "Browse, manage and pass along this workflow's workspace files"+ component_kind = "square"+ handles = (+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ annotations = {"destructive": True, "readonly": False, "open_world": False}+ task_queue = TaskQueue.DEFAULT+ usable_as_tool = False+ # hideInputSection only: unlike processManager this node produces output+ # worth seeing and dragging, so the Output section stays.+ ui_hints = {"isGalleryPanel": True, "hideInputSection": True}++ Params = GalleryParams+ Output = GalleryOutput++ @Operation("list")+ async def list_files(self, ctx: NodeContext, params: GalleryParams) -> Any:+ workspace_dir = ctx.workspace_dir or (ctx.raw or {}).get("workspace_dir")+ if not workspace_dir:+ raise NodeUserError(+ "This workflow has no workspace yet. Save and run it once first."+ )++ if params.selection:+ return await self._emit_selection(ctx, params, str(workspace_dir))++ if params.pattern:+ result = await list_matching(+ str(workspace_dir),+ pattern=params.pattern,+ path=params.path,+ workflow_id=ctx.workflow_id,+ limit=params.limit,+ )+ else:+ result = await list_directory(+ str(workspace_dir),+ path=params.path,+ workflow_id=ctx.workflow_id,+ limit=params.limit,+ )++ rows = result["entries"]+ files = [to_file_ref(r, ctx.workflow_id) for r in rows if not r["is_dir"]]+ directories = [r["path"] for r in rows if r["is_dir"]]++ return GalleryOutput(+ path=result["path"],+ files=files,+ directories=directories if params.include_dirs else [],+ count=len(files),+ truncated=result["truncated"],+ )++ async def _emit_selection(+ self, ctx: NodeContext, params: GalleryParams, workspace_dir: str+ ) -> Any:+ """Emit exactly the pinned files, reporting any that have gone.++ A missing selection is not automatically an error: the node that+ writes the file may simply not have run yet in this execution. Only+ an entirely missing selection fails.+ """+ import mimetypes+ from datetime import datetime++ from services.media.workspace import resolve_media++ files: list = []+ missing: list = []+ for rel in params.selection:+ try:+ target = resolve_media(rel, workspace_dir=workspace_dir)+ except NodeUserError:+ missing.append(rel)+ continue+ if not target.is_file():+ missing.append(rel)+ continue+ stat = target.stat()+ files.append(+ to_file_ref(+ {+ "name": target.name,+ "path": str(rel).strip("/"),+ "is_dir": False,+ "size_bytes": stat.st_size,+ "modified_at": datetime.fromtimestamp(stat.st_mtime).isoformat(),+ "mime_type": mimetypes.guess_type(target.name)[0],+ "url": None,+ },+ ctx.workflow_id,+ )+ )++ if missing and not files:+ raise NodeUserError(+ "None of the selected files exist in this workspace: "+ + ", ".join(missing[:5])+ )++ return GalleryOutput(+ path=params.path or "",+ files=files,+ directories=[],+ count=len(files),+ truncated=False,+ missing=missing,+ )+++# --- self-registration on import -------------------------------------------+from services.ws_handler_registry import register_ws_handlers # noqa: E402++from ._handlers import WS_HANDLERS # noqa: E402++register_ws_handlers(WS_HANDLERS)+++__all__ = [+ "WS_HANDLERS",+ "GalleryNode",+ "GalleryOutput",+ "GalleryParams",+ "WORKSPACE_LIST_DEFAULT",+]diff --git a/server/nodes/filesystem/gallery/_handlers.py b/server/nodes/filesystem/gallery/_handlers.pynew file mode 100644index 00000000..cc7a66b9--- /dev/null+++ b/server/nodes/filesystem/gallery/_handlers.py@@ -0,0 +1,76 @@+"""WebSocket commands for the Gallery panel.++Listing lives on the WebSocket rather than HTTP because the consumer is the+parameter panel, which already holds an authenticated socket with request+correlation — a second HTTP surface would mean a second auth path and a+second error envelope for no gain. ``GET /api/workspace/{id}/files/{path}``+stays the *content* channel (preview, download, Range).++``@ws_response`` rather than ``@ws_handler``: the latter logs every exception+at ERROR with a traceback, which breaks the NodeUserError contract that a+user-correctable failure is one WARN line.+"""++from __future__ import annotations++from typing import Any, Awaitable, Callable, Dict++from fastapi import WebSocket++from core.logging import get_logger+from services.plugin.ws import ws_response++from ._service import WORKSPACE_LIST_DEFAULT, list_directory, list_matching++logger = get_logger(__name__)+++async def _root_for(workflow_id: str, *, mutating: bool = False):+ """Resolve the workspace directory for a request from the editor.++ Mutating callers refuse the anonymous ``default`` workspace: an id that+ does not resolve — a stale tab, a workflow deleted in another window —+ would otherwise silently modify files belonging to a different context.+ """+ from core.container import container+ from services.workspace_locator import resolve_workspace_root++ return await resolve_workspace_root(+ workflow_id, container.database(), allow_default=not mutating+ )+++@ws_response+async def handle_list_workspace_files(+ data: Dict[str, Any], websocket: WebSocket+) -> Dict[str, Any]:+ """List one directory of a workflow's workspace, or glob across it."""+ workflow_id = str(data.get("workflow_id") or "")+ root = await _root_for(workflow_id)++ pattern = str(data.get("pattern") or "").strip()+ limit = int(data.get("limit") or WORKSPACE_LIST_DEFAULT)+ path = str(data.get("path") or "")++ if pattern:+ result = await list_matching(+ str(root),+ pattern=pattern,+ path=path,+ workflow_id=workflow_id or None,+ limit=limit,+ )+ else:+ result = await list_directory(+ str(root), path=path, workflow_id=workflow_id or None, limit=limit+ )++ return {"success": True, "workflow_id": workflow_id, **result}+++WS_HANDLERS: Dict[str, Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]] = {+ "list_workspace_files": handle_list_workspace_files,+}+++__all__ = ["WS_HANDLERS", "handle_list_workspace_files"]diff --git a/server/nodes/filesystem/gallery/_service.py b/server/nodes/filesystem/gallery/_service.pynew file mode 100644index 00000000..8495753d--- /dev/null+++ b/server/nodes/filesystem/gallery/_service.py@@ -0,0 +1,185 @@+"""Workspace listing — the shared body behind the node op and the WS handlers.++Enumeration itself is delegated to :class:`WorkspaceBackend`, which already+filters symlink escapes through ``_safe_child``. This module owns the two+things the backend does not: the **wire shape** and the **caps**.++The wire shape is the load-bearing part. ``WorkspaceBackend._file_info``+emits ``"/audio/x.wav"`` with a leading slash, but every consumer of a file+reference wants it relative:++ POSIX : Path('/audio/x.wav').is_absolute() -> True+ Windows: Path('/audio/x.wav').is_absolute() -> False++so ``resolve_media`` takes its absolute-path branch on Linux only, fails+``relative_to(root)``, and raises "outside this workflow's workspace" — while+the same path works on a Windows dev box. A leading slash is therefore a+production-only bug, and it is converted here rather than in ``_file_info``,+whose current shape ``fsSearch`` output and its LLM-facing prompt depend on.+"""++from __future__ import annotations++import asyncio+import mimetypes+from pathlib import Path+from typing import Any, Dict, List, Optional++# Bounds the response, not the walk: ls_info materialises the directory+# before we slice it. The only in-repo precedent is the MCP tool's 1000.+WORKSPACE_LIST_LIMIT = 1000+WORKSPACE_LIST_DEFAULT = 500+++def _relative(virtual_path: str) -> str:+ """``/audio/x.wav`` or ``/audio/`` -> ``audio/x.wav`` / ``audio``."""+ return virtual_path.strip("/")+++def _entry_url(workflow_id: Optional[str], rel_path: str, is_dir: bool) -> Optional[str]:+ if is_dir or not workflow_id:+ return None+ from services.media.workspace import workspace_file_url++ return workspace_file_url(workflow_id, rel_path)+++def _to_row(info: Dict[str, Any], workflow_id: Optional[str]) -> Dict[str, Any]:+ """One ``_file_info`` dict -> the wire row, a strict subset of FileRef.++ Keeping the field names a subset means the client can lift a row into a+ ``FileRef`` without a round trip: no ambiguity about which name wins.+ """+ is_dir = bool(info.get("is_dir"))+ rel = _relative(str(info.get("path", "")))+ name = rel.rsplit("/", 1)[-1]+ mime = None if is_dir else (mimetypes.guess_type(name)[0] or "application/octet-stream")++ return {+ "name": name,+ "path": rel,+ "is_dir": is_dir,+ "size_bytes": int(info.get("size") or 0),+ "modified_at": info.get("modified_at"),+ "mime_type": mime,+ "url": _entry_url(workflow_id, rel, is_dir),+ }+++def _sort_key(row: Dict[str, Any]):+ # Directories first, then case-insensitive name. Not cosmetic: it means+ # truncating at the cap can never strip navigation out of the response.+ return (not row["is_dir"], row["name"].lower())+++async def list_directory(+ workspace_dir: str,+ *,+ path: str = "",+ workflow_id: Optional[str] = None,+ limit: int = WORKSPACE_LIST_DEFAULT,+) -> Dict[str, Any]:+ """List one directory. Never recursive.++ ``glob_info`` uses ``rglob``, so a ``*`` pattern would walk the entire+ tree unbounded — a multi-second handler and a multi-megabyte payload.+ Directory-at-a-time is what a tree view needs anyway.+ """+ from .._backend import get_backend, normalize_virtual_path++ capped = max(1, min(int(limit or WORKSPACE_LIST_DEFAULT), WORKSPACE_LIST_LIMIT))+ virtual = normalize_virtual_path(path or "/")+ rel = _relative(virtual)++ root = Path(workspace_dir)++ # Probe BEFORE building the backend: get_backend mkdirs the root, so+ # asking afterwards always answers True and the panel could never tell+ # "no workspace yet" from "this folder is empty" — which is the whole+ # reason these two flags exist, since ls_info returns [] for both.+ target = root / rel if rel else root+ workspace_exists = root.is_dir()+ path_exists = target.is_dir()++ backend = get_backend({}, {"workspace_dir": str(root)})++ # iterdir() on a large directory blocks; this runs on the shared WS loop.+ infos: List[Dict[str, Any]] = (+ await asyncio.to_thread(backend.ls_info, virtual) if path_exists else []+ )++ rows = sorted((_to_row(info, workflow_id) for info in infos), key=_sort_key)+ truncated = len(rows) > capped++ return {+ "path": rel,+ "parent": None if not rel else rel.rsplit("/", 1)[0] if "/" in rel else "",+ "entries": rows[:capped],+ "count": min(len(rows), capped),+ "truncated": truncated,+ "workspace_exists": workspace_exists,+ "path_exists": path_exists,+ }+++async def list_matching(+ workspace_dir: str,+ *,+ pattern: str,+ path: str = "",+ workflow_id: Optional[str] = None,+ limit: int = WORKSPACE_LIST_DEFAULT,+) -> Dict[str, Any]:+ """Recursive glob under ``path``. Files only — ``glob_info`` filters dirs.++ Used by the node's execution path and by panel search, both of which+ want to escape the current directory. Same cap applies.+ """+ from .._backend import get_backend, normalize_virtual_path++ capped = max(1, min(int(limit or WORKSPACE_LIST_DEFAULT), WORKSPACE_LIST_LIMIT))+ virtual = normalize_virtual_path(path or "/")++ backend = get_backend({}, {"workspace_dir": str(workspace_dir)})+ infos: List[Dict[str, Any]] = await asyncio.to_thread(+ backend.glob_info, pattern or "*", virtual+ )++ rows = sorted((_to_row(info, workflow_id) for info in infos), key=_sort_key)+ return {+ "path": _relative(virtual),+ "pattern": pattern or "*",+ "entries": rows[:capped],+ "count": min(len(rows), capped),+ "truncated": len(rows) > capped,+ }+++def to_file_ref(row: Dict[str, Any], workflow_id: Optional[str]) -> Dict[str, Any]:+ """Wire row -> serialized ``FileRef``.++ Always ``kind="file"``, even for a ``.wav``: ``kind="audio"`` asserts the+ container was probed by ``inspect_audio``, and this only guessed a mime+ type from the extension. Claiming the richer kind with a null duration+ would mis-bill a per-second provider downstream.+ """+ from services.media.refs import FileRef++ return FileRef(+ path=row["path"],+ workflow_id=workflow_id,+ filename=row["name"],+ mime_type=row.get("mime_type") or "application/octet-stream",+ size_bytes=row.get("size_bytes") or 0,+ modified_at=row.get("modified_at"),+ url=row.get("url"),+ ).model_dump(mode="json")+++__all__ = [+ "WORKSPACE_LIST_DEFAULT",+ "WORKSPACE_LIST_LIMIT",+ "list_directory",+ "list_matching",+ "to_file_ref",+]diff --git a/server/nodes/filesystem/gallery/meta.json b/server/nodes/filesystem/gallery/meta.jsonnew file mode 100644index 00000000..9604cb8d--- /dev/null+++ b/server/nodes/filesystem/gallery/meta.json@@ -0,0 +1 @@+{"color": "#8be9fd"}diff --git a/server/tests/nodes/test_gallery.py b/server/tests/nodes/test_gallery.pynew file mode 100644index 00000000..a7d18e65--- /dev/null+++ b/server/tests/nodes/test_gallery.py@@ -0,0 +1,312 @@+"""Contract for the Gallery listing surface.++The path shape is the thing under test. ``WorkspaceBackend._file_info``+emits a leading slash; every consumer of a file reference wants it relative;+and the difference only fails on POSIX, because+``Path('/audio/x.wav').is_absolute()`` is True there and False on Windows.+A leading slash would therefore drag fine on a Windows dev box and break in+production, so the round-trip assertion below is the regression test that+matters most here.+"""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from nodes.filesystem.gallery._service import (+ WORKSPACE_LIST_LIMIT,+ list_directory,+ list_matching,+ to_file_ref,+)++pytestmark = pytest.mark.unit++WORKFLOW_ID = "019f99e2dc997cf390193ad3e6260de1"+++def workspace(tmp_path):+ (tmp_path / "audio").mkdir()+ (tmp_path / "downloads").mkdir()+ (tmp_path / "audio" / "greeting.wav").write_bytes(b"RIFFDATA")+ (tmp_path / "chart.png").write_bytes(b"PNGDATA")+ (tmp_path / "notes.txt").write_text("hello")+ return tmp_path+++class TestPathShape:+ async def test_paths_are_relative_with_no_leading_slash(self, workspace):+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)++ for entry in result["entries"]:+ assert not entry["path"].startswith("/"), entry+ assert not entry["path"].endswith("/"), entry+ assert "\\" not in entry["path"], entry+ assert not Path(entry["path"]).is_absolute()++ async def test_a_listed_path_resolves_back_inside_the_workspace(self, workspace):+ """The regression test for the POSIX-only failure.++ A leading-slash path takes resolve_media's absolute branch on Linux,+ fails relative_to(root), and raises "outside this workflow's+ workspace" -- while working on Windows.+ """+ from services.media.workspace import read_media_bytes, resolve_media++ result = await list_directory(+ str(workspace), path="audio", workflow_id=WORKFLOW_ID+ )+ row = result["entries"][0]++ resolved = resolve_media(row["path"], workspace_dir=str(workspace))+ assert resolved.relative_to(workspace)+ assert read_media_bytes(row["path"], workspace_dir=str(workspace))[1] == b"RIFFDATA"++ async def test_a_listed_row_lifts_into_a_readable_file_ref(self, workspace):+ """What a drag onto a file parameter actually carries."""+ from services.media.refs import FileRef+ from services.media.workspace import coerce_file_param+ from types import SimpleNamespace++ result = await list_directory(+ str(workspace), path="audio", workflow_id=WORKFLOW_ID+ )+ ref = to_file_ref(result["entries"][0], WORKFLOW_ID)++ assert FileRef.model_validate(ref)+ ctx = SimpleNamespace(+ workspace_dir=str(workspace), node_id="n", workflow_id=WORKFLOW_ID+ )+ assert coerce_file_param(ref, ctx=ctx)[1] == b"RIFFDATA"++ async def test_listing_never_claims_a_richer_kind_than_it_probed(self, workspace):+ """A .wav listed is kind='file', not 'audio'.++ kind='audio' asserts inspect_audio ran; claiming it with a null+ duration would mis-bill a per-second provider downstream.+ """+ result = await list_directory(+ str(workspace), path="audio", workflow_id=WORKFLOW_ID+ )+ ref = to_file_ref(result["entries"][0], WORKFLOW_ID)++ assert ref["kind"] == "file"+ assert ref["filename"].endswith(".wav")+++class TestListingShape:+ async def test_directories_sort_before_files(self, workspace):+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)+ kinds = [entry["is_dir"] for entry in result["entries"]]++ assert kinds == sorted(kinds, reverse=True)++ async def test_urls_are_path_only_and_absent_for_directories(self, workspace):+ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)++ for entry in result["entries"]:+ if entry["is_dir"]:+ assert entry["url"] is None+ else:+ assert entry["url"].startswith(f"/api/workspace/{WORKFLOW_ID}/files/")+ assert "://" not in entry["url"]++ async def test_parent_is_empty_at_root_and_set_below(self, workspace):+ assert (await list_directory(str(workspace)))["parent"] is None+ assert (await list_directory(str(workspace), path="audio"))["parent"] == ""++ async def test_missing_directory_is_distinguishable_from_an_empty_one(+ self, workspace+ ):+ """ls_info returns [] for both; the panel must tell them apart."""+ empty = await list_directory(str(workspace), path="downloads")+ assert empty["entries"] == [] and empty["path_exists"] is True++ gone = await list_directory(str(workspace), path="nope")+ assert gone["entries"] == [] and gone["path_exists"] is False++ async def test_absent_workspace_reports_itself(self, tmp_path):+ result = await list_directory(str(tmp_path / "never-created"))++ assert result["workspace_exists"] is False+ assert result["entries"] == []+++class TestCaps:+ async def test_cap_truncates_and_reports(self, tmp_path):+ for index in range(30):+ (tmp_path / f"file-{index:03d}.txt").write_text("x")++ result = await list_directory(str(tmp_path), limit=10)++ assert result["count"] == 10+ assert result["truncated"] is True++ async def test_directories_survive_truncation(self, tmp_path):+ """Why dirs sort first: the cap must never strip navigation."""+ (tmp_path / "zzz_folder").mkdir()+ for index in range(30):+ (tmp_path / f"aaa-{index:03d}.txt").write_text("x")++ result = await list_directory(str(tmp_path), limit=5)++ assert any(entry["is_dir"] for entry in result["entries"])++ async def test_limit_is_clamped_to_the_hard_cap(self, tmp_path):+ (tmp_path / "a.txt").write_text("x")++ result = await list_directory(str(tmp_path), limit=10_000_000)++ assert result["count"] <= WORKSPACE_LIST_LIMIT+++class TestTraversal:+ @pytest.mark.parametrize("attack", ["../..", "../../etc", "~", "..\\.."])+ async def test_traversal_is_refused(self, workspace, attack):+ from services.plugin import NodeUserError++ (workspace.parent / "secret.txt").write_text("SECRET")++ with pytest.raises(NodeUserError):+ await list_directory(str(workspace), path=attack)++ @pytest.mark.parametrize("rooted", ["/etc", "C:/Windows", "/"])+ async def test_rooted_paths_are_reinterpreted_inside_the_workspace(+ self, workspace, rooted+ ):+ """These are not escapes and must not be refused.++ A leading slash is the *virtual* root (the workspace itself), and a+ drive prefix is stripped by _validate_virtual_path. '/etc' therefore+ means '<workspace>/etc'. The property under test is containment, not+ which mechanism enforces it.+ """+ from nodes.filesystem._backend import normalize_virtual_path, resolve_within++ resolved = resolve_within(workspace, normalize_virtual_path(rooted))+ assert resolved.is_relative_to(workspace)++ # And listing it simply finds nothing, rather than reading the host.+ result = await list_directory(str(workspace), path=rooted)+ assert result["entries"] == [] or all(+ not entry["path"].startswith("..") for entry in result["entries"]+ )++ async def test_glob_pattern_cannot_escape(self, workspace):+ from services.plugin import NodeUserError++ with pytest.raises((NodeUserError, ValueError)):+ await list_matching(str(workspace), pattern="../*", path="")+++class TestGlob:+ async def test_matches_recursively_and_returns_files_only(self, workspace):+ result = await list_matching(+ str(workspace), pattern="*.wav", workflow_id=WORKFLOW_ID+ )++ assert result["count"] == 1+ assert result["entries"][0]["path"] == "audio/greeting.wav"+ assert all(not entry["is_dir"] for entry in result["entries"])+++class TestNodeExecution:+ async def test_emits_file_refs_for_downstream_nodes(self, workspace):+ from tests.nodes._harness import NodeTestHarness # noqa: F401 (availability)+ from nodes.filesystem.gallery import GalleryNode, GalleryParams+ from types import SimpleNamespace++ ctx = SimpleNamespace(+ workspace_dir=str(workspace),+ workflow_id=WORKFLOW_ID,+ node_id="fm-1",+ raw={"workspace_dir": str(workspace)},+ )+ result = await GalleryNode().list_files(+ ctx, GalleryParams(path="audio")+ )++ assert result.count == 1+ assert result.files[0]["kind"] == "file"+ assert result.files[0]["path"] == "audio/greeting.wav"++ async def test_selection_reports_missing_without_failing(self, workspace):+ from nodes.filesystem.gallery import GalleryNode, GalleryParams+ from types import SimpleNamespace++ ctx = SimpleNamespace(+ workspace_dir=str(workspace),+ workflow_id=WORKFLOW_ID,+ node_id="fm-1",+ raw={"workspace_dir": str(workspace)},+ )+ result = await GalleryNode().list_files(+ ctx,+ GalleryParams(selection=["audio/greeting.wav", "audio/gone.wav"]),+ )++ assert result.count == 1+ assert result.missing == ["audio/gone.wav"]++ async def test_selection_that_is_entirely_missing_is_a_user_error(self, workspace):+ from nodes.filesystem.gallery import GalleryNode, GalleryParams+ from services.plugin import NodeUserError+ from types import SimpleNamespace++ ctx = SimpleNamespace(+ workspace_dir=str(workspace),+ workflow_id=WORKFLOW_ID,+ node_id="fm-1",+ raw={"workspace_dir": str(workspace)},+ )+ with pytest.raises(NodeUserError):+ await GalleryNode().list_files(+ ctx, GalleryParams(selection=["nope.wav"])+ )++ async def test_output_stays_well_under_the_temporal_warning_budget(self, tmp_path):+ """1000 FileRef rows must not approach the payload ceiling."""+ import orjson++ from nodes.filesystem.gallery import GalleryNode, GalleryParams+ from services.media.limits import TEMPORAL_PAYLOAD_ERROR_BYTES+ from types import SimpleNamespace++ for index in range(1000):+ (tmp_path / f"generated-file-name-{index:04d}.wav").write_bytes(b"x")++ ctx = SimpleNamespace(+ workspace_dir=str(tmp_path),+ workflow_id=WORKFLOW_ID,+ node_id="fm-1",+ raw={"workspace_dir": str(tmp_path)},+ )+ result = await GalleryNode().list_files(ctx, GalleryParams(limit=1000))++ size = len(orjson.dumps(result.model_dump(mode="json")))+ assert size < TEMPORAL_PAYLOAD_ERROR_BYTES+++class TestWorkspaceContainmentOfSymlinks:+ @pytest.mark.skipif(+ not hasattr(__import__("os"), "symlink"), reason="no symlink support"+ )+ async def test_a_symlink_escaping_the_workspace_is_not_listed(+ self, workspace, tmp_path+ ):+ import os++ outside = tmp_path.parent / "outside-secret.txt"+ outside.write_text("SECRET")+ try:+ os.symlink(outside, workspace / "escape.txt")+ except (OSError, NotImplementedError):+ pytest.skip("symlink creation not permitted on this platform")++ result = await list_directory(str(workspace), workflow_id=WORKFLOW_ID)++ assert "escape.txt" not in [entry["name"] for entry in result["entries"]]diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.pyindex a7bff7ec..cae627c3 100644--- a/server/tests/test_node_spec.py+++ b/server/tests/test_node_spec.py@@ -929,8 +929,8 @@ class TestNodeSpecContractInvariants:"isMonitorPanel","isTaskManagerPanel","isProcessManagerPanel",- # fileManager: workspace file browser with drag-to-parameter.- "isFileManagerPanel",+ # gallery: workspace file browser with drag-to-parameter.+ "isGalleryPanel","showLocationPanel","isAndroidToolkit","isChatTrigger",