diff --git a/coderunner/agent/loop.py b/coderunner/agent/loop.py index a6f8fac..a77b99b 100644 --- a/coderunner/agent/loop.py +++ b/coderunner/agent/loop.py @@ -46,7 +46,7 @@ - For a long task (more than about five steps), first write a short plan with plan_update, once, and keep to it: mark steps done as they finish; rewrite it only when the approach must change. Short tasks need no plan. - The owner's shared folders are searchable with files_search (text, code, documents, images, audio, video). Link a file you used by its name and full path, as [Lease.pdf](/Users/me/Documents/Lease.pdf), or in angle brackets when the path has spaces, as [Lease.pdf](); {owner} opens it from the answer. - Save lasting preferences and facts with memory_save. Never store secrets. -- Save files you make for {owner} in /app/uploads/outputs: {owner} can open only those. +- Save files you make for {owner} in /app/uploads/outputs and link them: a click saves one to {owner}'s Downloads. {owner} can open only those. - Only your final message reaches {owner}, as a chat reply. A call's say field may carry a few words on what you are doing ("Checking Skyscanner for the 12th"), shown briefly as a status line; leave it out when there is nothing new. Never mention tools, clicks, element numbers, errors, timeouts or retries. - tell_owner keeps a finding you will want in the answer (a price, a choice you made), when you have no tool call to write beside. Your final message still holds everything. - When a site will not show what you need, get it from another site that has it before deciding it cannot be done. When only part can be found, answer with that part in the form asked (a table with the rows you have) and say in one sentence what is missing. diff --git a/coderunner/files/attached.py b/coderunner/files/attached.py index 3ea1631..00067cd 100644 --- a/coderunner/files/attached.py +++ b/coderunner/files/attached.py @@ -254,3 +254,59 @@ async def for_the_model(ids: list[str], media, vision: bool, sandbox: bool) -> t if sandbox: note += f"\nCode in the sandbox finds each one under {SANDBOX_DIR}//." return note, images, shown + + +def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> pathlib.Path: + """A file a task made, saved where a browser saves a download: the owner's Downloads folder, under its own + name, or "name (2).ext" beside a different file of that name. Clicking the same file again finds the one saved + before rather than making another. Never executable, whatever the sandbox made it, and never half-written: + the name is taken only once the whole file is there.""" + folder = folder or pathlib.Path.home() / "Downloads" + folder.mkdir(parents=True, exist_ok=True) + stem, suffix = copy.stem, copy.suffix + tmp = None + try: + for n in range(1, 1000): + target = folder / (copy.name if n == 1 else f"{stem} ({n}){suffix}") + if target.is_symlink() or target.exists(): + if _saved_before(copy, target): + return target + continue + if tmp is None: + tmp = _hidden_copy(copy, folder) + try: + os.link(tmp, target) # the name, given only to the whole file and never over another + except FileExistsError: + if _saved_before(copy, target): # a click at the same moment saved the same file + return target + continue + return target + finally: + if tmp is not None: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + raise OSError("no free name in Downloads") + + +def _hidden_copy(copy: pathlib.Path, folder: pathlib.Path) -> pathlib.Path: + """The whole file, copied under a hidden name in the folder it is saved to: owner read-write only.""" + fd, name = tempfile.mkstemp(dir=folder, prefix=".coderunner-", suffix=".part") + try: + with os.fdopen(fd, "wb") as out, open(copy, "rb") as src: + shutil.copyfileobj(src, out) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(name) + raise + return pathlib.Path(name) + + +def _saved_before(copy: pathlib.Path, target: pathlib.Path) -> bool: + """target is this same file saved before: a plain file, not executable, with the same bytes. One that cannot + be read is someone else's.""" + import filecmp + try: + return not target.is_symlink() and target.is_file() and not target.stat().st_mode & 0o111 and \ + filecmp.cmp(copy, target, shallow=False) + except OSError: + return False diff --git a/coderunner/server/gateway.py b/coderunner/server/gateway.py index 424537e..fdc0d3d 100644 --- a/coderunner/server/gateway.py +++ b/coderunner/server/gateway.py @@ -599,7 +599,7 @@ async def sandbox_file(request: Request): async def open_file(request: Request): """A file an answer links to, or the search box found, opened on this computer when the owner clicks it: - only a file in the shared folders. Documents, pictures, sound and video open in their usual app; anything + a file in the shared folders, or one a task made (saved to Downloads first). Documents, pictures, sound and video open in their usual app; anything that could run (an app, a script, code) is shown in Finder instead, so a link written by a model never starts a program. A folder (search finds those too) is shown in Finder: an app is a folder as well.""" from ..files import attached @@ -626,7 +626,11 @@ async def open_file(request: Request): copy = await asyncio.to_thread(attached.snapshot_output, relative) if copy is None: return JSONResponse({"error": "That file is not in the assistant's outputs folder."}, status_code=404) - path, made = copy, True + # Clicked, it is the owner's: saved to Downloads like a browser download, then opened or shown there. + try: + path, made = await asyncio.to_thread(attached.to_downloads, copy), True + except OSError: + return JSONResponse({"error": "It could not be saved to your Downloads folder."}, status_code=500) shared = not made and index is not None and (path.is_file() or path.is_dir()) and \ index.folders.inside(str(path)) if not (made or shared): @@ -641,11 +645,17 @@ async def open_file(request: Request): argv = ["open", str(path)] if opens else ["open", "-R", str(path)] else: argv = ["xdg-open", str(path if opens else path.parent)] - done = await asyncio.to_thread(subprocess.run, argv, capture_output=True, timeout=20) + try: + failed = (await asyncio.to_thread(subprocess.run, argv, capture_output=True, timeout=20)).returncode + except (OSError, subprocess.TimeoutExpired): # no opener here (xdg-open missing), or it hung + failed = True svc.audit.write("file.opened", path=str(path), shown=not opens, origin=principal(request)) - if done.returncode: + saved = {"saved": str(path)} if made else {} + if failed: + if made: + return JSONResponse({"opened": False, "shown": False, **saved}) return JSONResponse({"error": "It could not be opened."}, status_code=500) - return JSONResponse({"opened": opens, "shown": not opens}) + return JSONResponse({"opened": opens, "shown": not opens, **saved}) async def files(request: Request): """GET without `q`: the index's status. GET with `q`: the files that answer it, best first (`kind` keeps diff --git a/coderunner/server/web/app/app.js b/coderunner/server/web/app/app.js index 74feefe..3470f16 100644 --- a/coderunner/server/web/app/app.js +++ b/coderunner/server/web/app/app.js @@ -1207,8 +1207,10 @@ function showEvent(e) { // A file an answer links to: opened on this computer by the assistant (only from the shared folders). document.addEventListener("open-file", async (event) => { - try { await api("/api/files/open", {method: "POST", body: JSON.stringify({path: event.detail.path})}); } - catch (err) { notice(err.message); } + try { + const done = await api("/api/files/open", {method: "POST", body: JSON.stringify({path: event.detail.path})}); + if (done?.saved) notice(`Saved to Downloads: ${done.saved.split("/").pop()}`); + } catch (err) { notice(err.message); } }); function listen() { diff --git a/tests/test_attached.py b/tests/test_attached.py index bf8a42f..9dc8cff 100644 --- a/tests/test_attached.py +++ b/tests/test_attached.py @@ -395,5 +395,109 @@ async def test_a_file_too_large_is_refused_and_a_task_names_its_files(self): self.assertEqual(empty.status_code, 400) +class DownloadsTests(unittest.TestCase): + """A file a task made, saved into a Downloads folder (a temporary one here).""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = pathlib.Path(tmp.name).resolve() + self.made, self.folder = root / "outputs", root / "Downloads" + self.made.mkdir() + self.folder.mkdir() + + def make(self, name, data, mode=0o600): + path = self.made / name + path.write_bytes(data) + os.chmod(path, mode) + return path + + def names(self): + return sorted(p.name for p in self.folder.iterdir()) + + def test_a_failed_copy_leaves_nothing_behind_and_a_retry_takes_the_name(self): + report = self.make("report.txt", b"hello world, the whole report") + real = attached.shutil.copyfileobj + + def half(src, out, *args): + out.write(src.read(5)) + out.flush() + raise OSError(28, "No space left on device") + with mock.patch.object(attached.shutil, "copyfileobj", half): + with self.assertRaises(OSError): + attached.to_downloads(report, self.folder) + self.assertEqual(self.names(), []) + with mock.patch.object(attached.shutil, "copyfileobj", real): + saved = attached.to_downloads(report, self.folder) + self.assertEqual(saved, self.folder / "report.txt") + self.assertEqual(saved.read_bytes(), report.read_bytes()) + self.assertEqual(self.names(), ["report.txt"]) + + def test_a_saved_file_is_never_executable(self): + script = self.make("setup.sh", b"echo hi", 0o700) + saved = attached.to_downloads(script, self.folder) + self.assertEqual(saved, self.folder / "setup.sh") + self.assertFalse(saved.stat().st_mode & 0o111) + + def test_the_same_file_already_there_but_executable_is_not_handed_back(self): + script = self.make("setup.sh", b"echo hi") + (self.folder / "setup.sh").write_bytes(b"echo hi") + os.chmod(self.folder / "setup.sh", 0o700) + saved = attached.to_downloads(script, self.folder) + self.assertEqual(saved, self.folder / "setup (2).sh") + self.assertFalse(saved.stat().st_mode & 0o111) + self.assertEqual(saved.read_bytes(), b"echo hi") + # Saved again: the copy made just now, not a third one. + self.assertEqual(attached.to_downloads(script, self.folder), saved) + self.assertEqual(self.names(), ["setup (2).sh", "setup.sh"]) + + def test_the_same_file_is_found_again_and_a_different_one_gets_a_number(self): + pdf = self.make("plan.pdf", b"%PDF-1") + first = attached.to_downloads(pdf, self.folder) + self.assertEqual(attached.to_downloads(pdf, self.folder), first) + pdf.write_bytes(b"%PDF-2") + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertEqual((self.folder / "plan.pdf").read_bytes(), b"%PDF-1") + self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) + + def test_a_link_of_that_name_is_passed_over(self): + pdf = self.make("plan.pdf", b"%PDF") + elsewhere = self.made / "elsewhere.pdf" + elsewhere.write_bytes(b"%PDF") + (self.folder / "plan.pdf").symlink_to(elsewhere) + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertTrue((self.folder / "plan.pdf").is_symlink()) + self.assertEqual(elsewhere.read_bytes(), b"%PDF") + + def test_a_disk_without_hard_links_says_so_and_leaves_nothing(self): + pdf = self.make("plan.pdf", b"%PDF") + with mock.patch.object(attached.os, "link", side_effect=PermissionError(1, "Operation not permitted")): + with self.assertRaises(OSError): + attached.to_downloads(pdf, self.folder) + self.assertEqual(self.names(), []) + + def test_two_clicks_at_once_save_one_copy(self): + pdf = self.make("plan.pdf", b"%PDF") + real = os.link + + def other_click_first(src, dst): + # The other click links its whole copy to the name between this one's look and its link. + (self.folder / "plan.pdf").write_bytes(b"%PDF") + os.chmod(self.folder / "plan.pdf", 0o600) + return real(src, dst) + with mock.patch.object(attached.os, "link", other_click_first): + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan.pdf") + self.assertEqual(self.names(), ["plan.pdf"]) + + @unittest.skipIf(os.geteuid() == 0, "root reads any file") + def test_a_file_of_that_name_that_cannot_be_read_is_passed_over(self): + pdf = self.make("plan.pdf", b"%PDF") + locked = self.folder / "plan.pdf" + locked.write_bytes(b"%PDX") + os.chmod(locked, 0) + self.addCleanup(os.chmod, locked, 0o600) + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gateway.py b/tests/test_gateway.py index ab4ee97..d75be2f 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -248,7 +248,7 @@ def run(argv, **kwargs): self.assertEqual(ran, [["open", str(shared / "Lease.pdf")], ["open", "-R", str(shared / "run.command")], ["open", "-R", str(shared / "tool.py")]]) - async def test_a_file_a_task_made_opens_by_its_path_here_or_in_the_sandbox(self): + async def test_a_file_a_task_made_is_saved_to_downloads_and_opened_there_by_its_path_here_or_in_the_sandbox(self): import os import subprocess import tempfile @@ -261,6 +261,10 @@ async def test_a_file_a_task_made_opens_by_its_path_here_or_in_the_sandbox(self) (elsewhere / "private.pdf").write_bytes(b"%PDF") (outputs / "link.pdf").symlink_to(elsewhere / "private.pdf") home = pathlib.Path(tempfile.mkdtemp()).resolve() + user = pathlib.Path(tempfile.mkdtemp()).resolve() + downloads = user / "Downloads" + downloads.mkdir() + (downloads / "setup.sh").write_text("someone else's") self.svc.files = None ran = [] @@ -271,27 +275,56 @@ def run(argv, **kwargs): with mock.patch("coderunner.server.gateway.subprocess.run", run), \ mock.patch("coderunner.server.gateway.sys.platform", "darwin"), \ mock.patch("coderunner.files.attached.outputs_dir", return_value=outputs), \ - mock.patch("coderunner.core.paths.home", return_value=home): + mock.patch("coderunner.core.paths.home", return_value=home), \ + mock.patch("pathlib.Path.home", return_value=user): async with self.client() as client: post = lambda path: client.post("/api/files/open", json={"path": str(path)}, headers=admin) # noqa: E731 + pdf = str(downloads / "regional-restaurants-india.pdf") self.assertEqual((await post("/app/uploads/outputs/regional-restaurants-india.pdf")).json(), - {"opened": True, "shown": False}) + {"opened": True, "shown": False, "saved": pdf}) + # Clicked again, by its path here: the copy saved before, not a second one. self.assertEqual((await post(outputs / "regional-restaurants-india.pdf")).json(), - {"opened": True, "shown": False}) - self.assertEqual((await post("/app/uploads/outputs/setup.sh")).json(), {"opened": False, "shown": True}) + {"opened": True, "shown": False, "saved": pdf}) + # A different file of that name is left alone; what could run is shown in Finder, not run. + self.assertEqual((await post("/app/uploads/outputs/setup.sh")).json(), + {"opened": False, "shown": True, "saved": str(downloads / "setup (2).sh")}) # A link the sandbox left there leads nowhere outside it. self.assertEqual((await post("/app/uploads/outputs/link.pdf")).status_code, 404) self.assertEqual((await post("/app/uploads/outputs/../../../etc/hosts")).status_code, 404) gone = await post("/workspace/report.pdf") self.assertEqual(gone.status_code, 404) self.assertIn("inside the assistant's computer", gone.json()["error"]) - # What was opened is a copy outside the folder the sandbox writes, never the file there. - self.assertEqual([argv[:-1] for argv in ran], [["open"], ["open"], ["open", "-R"]]) - copies = [pathlib.Path(argv[-1]) for argv in ran] - self.assertTrue(all(home in copy.parents and outputs not in copy.parents for copy in copies)) - self.assertEqual([copy.name for copy in copies], ["regional-restaurants-india.pdf"] * 2 + ["setup.sh"]) - self.assertEqual(copies[0].read_bytes(), b"%PDF") - self.assertFalse(os.access(copies[2], os.X_OK)) + # What was opened is the copy in Downloads, never the file in the folder the sandbox writes. + self.assertEqual(ran, [["open", pdf], ["open", pdf], ["open", "-R", str(downloads / "setup (2).sh")]]) + self.assertEqual(sorted(p.name for p in downloads.iterdir()), + ["regional-restaurants-india.pdf", "setup (2).sh", "setup.sh"]) + # The sandbox made the script executable; the copy in Downloads is not. + self.assertFalse(os.stat(downloads / "setup (2).sh").st_mode & 0o111) + self.assertEqual((downloads / "regional-restaurants-india.pdf").read_bytes(), b"%PDF") + self.assertEqual((downloads / "setup.sh").read_text(), "someone else's") + self.assertFalse(os.access(downloads / "setup (2).sh", os.X_OK)) + + async def test_a_saved_file_is_still_named_when_nothing_here_can_open_it(self): + import subprocess + import tempfile + from unittest import mock + outputs = pathlib.Path(tempfile.mkdtemp()).resolve() + (outputs / "report.pdf").write_bytes(b"%PDF") + user = pathlib.Path(tempfile.mkdtemp()).resolve() + self.svc.files = None + admin = {"Authorization": "Bearer " + ADMIN} + for problem in (FileNotFoundError(2, "No such file or directory: 'xdg-open'"), + subprocess.TimeoutExpired(["xdg-open"], 20)): + with mock.patch("coderunner.server.gateway.subprocess.run", side_effect=problem), \ + mock.patch("coderunner.server.gateway.sys.platform", "linux"), \ + mock.patch("coderunner.files.attached.outputs_dir", return_value=outputs), \ + mock.patch("coderunner.core.paths.home", return_value=pathlib.Path(tempfile.mkdtemp())), \ + mock.patch("pathlib.Path.home", return_value=user): + async with self.client() as client: + got = await client.post("/api/files/open", json={"path": "/app/uploads/outputs/report.pdf"}, + headers=admin) + self.assertEqual((got.status_code, got.json()), + (200, {"opened": False, "shown": False, "saved": str(user / "Downloads" / "report.pdf")})) def test_a_copy_is_taken_without_following_a_link_at_any_step(self): import os