bots-garden/sidekickspublic Fork
⑂ 849febe
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/sidekicks.git
git clone ssh://git@rickub.com/bots-garden/sidekicks.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#70 Dupliquer des fichiers et dossiers dans le panel Agents

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-09T06:24:48+01:00 Browse files
849febe parent: e60cdc9
modified .tickets/issues/0070-gerer-les-fichiers-du-panel-agents-renommer-supp.yaml +16 -2
@@ -6,7 +6,7 @@ author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-09T04:42:57.000Z
9-updatedAt: 2026-11-09T05:09:11.000Z
9+updatedAt: 2026-11-09T05:23:59.000Z
1010 labels:
1111 - kind::feature
1212 - area::workspace
@@ -54,5 +54,19 @@ comments:
5454 Logique pure dans [fileSelection.ts](frontend/src/lib/fileSelection.ts), testée.
5555 - Vérifié dans l'application (Linux, Xvfb) : colorisation, sélection, glisser-déposer, F2, menu, Move to…,
5656 suppression de 2 fichiers vers la corbeille.
57- - Pas fait : **dupliquer** (copie de dossiers en local et dans un container) — à rouvrir si besoin.
5857 - Textes EN + FR ; guide « fichiers et terminal » et référence `WorkspaceService` EN + FR.
58+ - id: 2
59+ author:
60+ name: k33g
61+ email: ph.charriere@gmail.com
62+ createdAt: 2026-11-09T05:23:59.000Z
63+ body: |
64+ **Dupliquer** ajouté, à la demande.
65+ - Go : `Workspace.Copy` (local : fichiers avec leurs droits, liens symboliques copiés comme liens ;
66+ container / sbx : `cp -RPp`), dans les tests de contrat (local et alpine) ; `WorkspaceService.Duplicate`
67+ copie à côté de l'original sous `<nom>-copy<.ext>`, puis `-copy-2`… ; un fichier protégé peut être dupliqué
68+ (la copie ne l'est pas), une copie qui tomberait dans un dossier protégé est refusée.
69+ - Interface : **Duplicate** dans le menu contextuel (une entrée ou la sélection) et ⌘D / Ctrl+D dans l'arbre ;
70+ les copies deviennent la sélection.
71+ - Vérifié dans l'application : dossier `notes` → `notes-copy` avec son contenu, `AGENTS.md` (protégé) → `AGENTS-copy.md`.
72+ - Docs EN + FR (guide et référence).
@@ -6,7 +6,7 @@ author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-09T04:42:57.000Z8 createdAt: 2026-11-09T04:42:57.000Z
9-updatedAt: 2026-11-09T05:09:11.000Z9+updatedAt: 2026-11-09T05:23:59.000Z
10 labels:10 labels:
11 - kind::feature11 - kind::feature
12 - area::workspace12 - area::workspace
@@ -54,5 +54,19 @@ comments:
54 Logique pure dans [fileSelection.ts](frontend/src/lib/fileSelection.ts), testée.54 Logique pure dans [fileSelection.ts](frontend/src/lib/fileSelection.ts), testée.
55 - Vérifié dans l'application (Linux, Xvfb) : colorisation, sélection, glisser-déposer, F2, menu, Move to…,55 - Vérifié dans l'application (Linux, Xvfb) : colorisation, sélection, glisser-déposer, F2, menu, Move to…,
56 suppression de 2 fichiers vers la corbeille.56 suppression de 2 fichiers vers la corbeille.
57- - Pas fait : **dupliquer** (copie de dossiers en local et dans un container) — à rouvrir si besoin.
58 - Textes EN + FR ; guide « fichiers et terminal » et référence `WorkspaceService` EN + FR.57 - Textes EN + FR ; guide « fichiers et terminal » et référence `WorkspaceService` EN + FR.
58+ - id: 2
59+ author:
60+ name: k33g
61+ email: ph.charriere@gmail.com
62+ createdAt: 2026-11-09T05:23:59.000Z
63+ body: |
64+ **Dupliquer** ajouté, à la demande.
65+ - Go : `Workspace.Copy` (local : fichiers avec leurs droits, liens symboliques copiés comme liens ;
66+ container / sbx : `cp -RPp`), dans les tests de contrat (local et alpine) ; `WorkspaceService.Duplicate`
67+ copie à côté de l'original sous `<nom>-copy<.ext>`, puis `-copy-2`… ; un fichier protégé peut être dupliqué
68+ (la copie ne l'est pas), une copie qui tomberait dans un dossier protégé est refusée.
69+ - Interface : **Duplicate** dans le menu contextuel (une entrée ou la sélection) et ⌘D / Ctrl+D dans l'arbre ;
70+ les copies deviennent la sélection.
71+ - Vérifié dans l'application : dossier `notes` → `notes-copy` avec son contenu, `AGENTS.md` (protégé) → `AGENTS-copy.md`.
72+ - Docs EN + FR (guide et référence).
modified docs/en/how-to/work-with-an-agents-files.md +1 -0
@@ -45,6 +45,7 @@ The link must lead to a file of the agent's folder: a path relative to the folde
4545 - **Select several entries**: ⌘-click (Ctrl-click on Windows and Linux) adds an entry to the selection or takes it out; ⇧-click selects every row up to it; ⌘A (Ctrl+A) selects every row shown. The actions below then apply to the whole selection.
4646 - **Rename**: hover the entry and click **✏️**, double-click it, or select it and press **F2**. Type the new name, Enter (Escape cancels). An open file follows its new name, even with unsaved changes.
4747 - **Move**: drag entries onto a folder (or onto a file, to go next to it; below the rows for the top of the folder). Without the mouse, right-click → **Move to…** and type the folder (empty for the top). A folder never goes inside itself, and nothing replaces an entry that already has the name.
48+- **Duplicate**: right-click → **Duplicate**, or select and press ⌘D (Ctrl+D). The copy goes next to the original, with `-copy` before the extension (`plan.md` → `plan-copy.md`, then `plan-copy-2.md`…); a folder is copied with its content. A protected file can be duplicated, and its copy is not protected — unless it lands in a protected folder, which is refused.
4849 - **Right-click** an entry for a menu with all these actions, and **Show where it is**.
4950 - **Delete**: hover the entry and click **🗑** (or **Delete** under the editor, or press **Delete** — ⌘⌫ on a Mac — in the tree), then confirm; with several entries selected, one confirmation covers them all. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so.
5051
@@ -45,6 +45,7 @@ The link must lead to a file of the agent's folder: a path relative to the folde
45 - **Select several entries**: ⌘-click (Ctrl-click on Windows and Linux) adds an entry to the selection or takes it out; ⇧-click selects every row up to it; ⌘A (Ctrl+A) selects every row shown. The actions below then apply to the whole selection.45 - **Select several entries**: ⌘-click (Ctrl-click on Windows and Linux) adds an entry to the selection or takes it out; ⇧-click selects every row up to it; ⌘A (Ctrl+A) selects every row shown. The actions below then apply to the whole selection.
46 - **Rename**: hover the entry and click **✏️**, double-click it, or select it and press **F2**. Type the new name, Enter (Escape cancels). An open file follows its new name, even with unsaved changes.46 - **Rename**: hover the entry and click **✏️**, double-click it, or select it and press **F2**. Type the new name, Enter (Escape cancels). An open file follows its new name, even with unsaved changes.
47 - **Move**: drag entries onto a folder (or onto a file, to go next to it; below the rows for the top of the folder). Without the mouse, right-click → **Move to…** and type the folder (empty for the top). A folder never goes inside itself, and nothing replaces an entry that already has the name.47 - **Move**: drag entries onto a folder (or onto a file, to go next to it; below the rows for the top of the folder). Without the mouse, right-click → **Move to…** and type the folder (empty for the top). A folder never goes inside itself, and nothing replaces an entry that already has the name.
48+- **Duplicate**: right-click → **Duplicate**, or select and press ⌘D (Ctrl+D). The copy goes next to the original, with `-copy` before the extension (`plan.md` → `plan-copy.md`, then `plan-copy-2.md`…); a folder is copied with its content. A protected file can be duplicated, and its copy is not protected — unless it lands in a protected folder, which is refused.
48 - **Right-click** an entry for a menu with all these actions, and **Show where it is**.49 - **Right-click** an entry for a menu with all these actions, and **Show where it is**.
49 - **Delete**: hover the entry and click **🗑** (or **Delete** under the editor, or press **Delete** — ⌘⌫ on a Mac — in the tree), then confirm; with several entries selected, one confirmation covers them all. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so.50 - **Delete**: hover the entry and click **🗑** (or **Delete** under the editor, or press **Delete** — ⌘⌫ on a Mac — in the tree), then confirm; with several entries selected, one confirmation covers them all. On this computer the file goes to the trash — restore it from the Finder if needed. In a container the deletion is final, and the confirmation says so.
50 51
modified docs/en/reference/agents-and-events.md +1 -0
@@ -187,6 +187,7 @@ A file opened for editing has `path, content, version`; `version` identifies the
187187 | `RemoveAll(agent, paths)` | Deletes several files and folders (a path inside another one of the list is skipped); nothing is deleted when one of them is protected or holds a protected file. Issue #70. |
188188 | `Rename(agent, from, to)` | Renames or moves a file or a folder to the path `to` (its folders are created); returns the new path. Refused when `to` exists, leaves the folder, is inside `from`, or when `from` or `to` is protected. Issue #70. |
189189 | `Move(agent, paths, dir)` | Moves files and folders into `dir` (`""` is the top), keeping their names; returns their new paths. Stops at the first that cannot move. Issue #70. |
190+| `Duplicate(agent, paths)` | Copies files and folders next to themselves under a free name with `-copy` before the extension; returns the copies' paths. A copy whose path is protected is refused. Issue #70. |
190191 | `CreateFolder(agent, dir, name)` | Creates an empty folder; refused if the name exists or contains `/`. Issue #70. |
191192 | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). |
192193 | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. |
@@ -187,6 +187,7 @@ A file opened for editing has `path, content, version`; `version` identifies the
187 | `RemoveAll(agent, paths)` | Deletes several files and folders (a path inside another one of the list is skipped); nothing is deleted when one of them is protected or holds a protected file. Issue #70. |187 | `RemoveAll(agent, paths)` | Deletes several files and folders (a path inside another one of the list is skipped); nothing is deleted when one of them is protected or holds a protected file. Issue #70. |
188 | `Rename(agent, from, to)` | Renames or moves a file or a folder to the path `to` (its folders are created); returns the new path. Refused when `to` exists, leaves the folder, is inside `from`, or when `from` or `to` is protected. Issue #70. |188 | `Rename(agent, from, to)` | Renames or moves a file or a folder to the path `to` (its folders are created); returns the new path. Refused when `to` exists, leaves the folder, is inside `from`, or when `from` or `to` is protected. Issue #70. |
189 | `Move(agent, paths, dir)` | Moves files and folders into `dir` (`""` is the top), keeping their names; returns their new paths. Stops at the first that cannot move. Issue #70. |189 | `Move(agent, paths, dir)` | Moves files and folders into `dir` (`""` is the top), keeping their names; returns their new paths. Stops at the first that cannot move. Issue #70. |
190+| `Duplicate(agent, paths)` | Copies files and folders next to themselves under a free name with `-copy` before the extension; returns the copies' paths. A copy whose path is protected is refused. Issue #70. |
190 | `CreateFolder(agent, dir, name)` | Creates an empty folder; refused if the name exists or contains `/`. Issue #70. |191 | `CreateFolder(agent, dir, name)` | Creates an empty folder; refused if the name exists or contains `/`. Issue #70. |
191 | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). |192 | `Attach(agent, hostPath)` | Joins a file of this computer to a message: returns its path in the agent's folder, to write after `$`. A file already in the folder is used where it is; any other is copied into `attachments/` (a free name, spaces turned into `-`, 5 MB at most). |
192 | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. |193 | `ChooseAttachment()` | Shows the native file dialog, from the home folder; returns the chosen path, or `""`. |
modified docs/fr/how-to/fichiers-et-terminal-d-un-agent.md +1 -0
@@ -45,6 +45,7 @@ Le lien doit mener à un fichier du dossier de l'agent : un chemin relatif au do
4545 - **Sélectionner plusieurs entrées** : ⌘-clic (Ctrl-clic sous Windows et Linux) ajoute une entrée à la sélection ou l'en retire ; ⇧-clic sélectionne toutes les lignes jusqu'à elle ; ⌘A (Ctrl+A) sélectionne toutes les lignes affichées. Les actions ci-dessous s'appliquent alors à toute la sélection.
4646 - **Renommer** : survolez l'entrée et cliquez sur **✏️**, double-cliquez dessus, ou sélectionnez-la et appuyez sur **F2**. Tapez le nouveau nom, Entrée (Échap annule). Un fichier ouvert suit son nouveau nom, même avec des modifications non enregistrées.
4747 - **Déplacer** : glissez les entrées sur un dossier (ou sur un fichier, pour aller à côté ; sous les lignes pour la racine du dossier). Sans la souris : clic droit → **Move to…** et tapez le dossier (vide pour la racine). Un dossier ne va jamais dans lui-même, et rien ne remplace une entrée qui porte déjà ce nom.
48+- **Dupliquer** : clic droit → **Duplicate**, ou sélectionnez et appuyez sur ⌘D (Ctrl+D). La copie se place à côté de l'original, avec `-copy` avant l'extension (`plan.md` → `plan-copy.md`, puis `plan-copy-2.md`…) ; un dossier est copié avec son contenu. Un fichier protégé peut être dupliqué, et sa copie n'est pas protégée — sauf si elle tombe dans un dossier protégé, ce qui est refusé.
4849 - **Clic droit** sur une entrée : un menu avec toutes ces actions, et **Afficher l'emplacement**.
4950 - **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur, ou appuyez sur **Suppr** — ⌘⌫ sur Mac — dans l'arbre), puis confirmez ; avec plusieurs entrées sélectionnées, une seule confirmation suffit. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit.
5051
@@ -45,6 +45,7 @@ Le lien doit mener à un fichier du dossier de l'agent : un chemin relatif au do
45 - **Sélectionner plusieurs entrées** : ⌘-clic (Ctrl-clic sous Windows et Linux) ajoute une entrée à la sélection ou l'en retire ; ⇧-clic sélectionne toutes les lignes jusqu'à elle ; ⌘A (Ctrl+A) sélectionne toutes les lignes affichées. Les actions ci-dessous s'appliquent alors à toute la sélection.45 - **Sélectionner plusieurs entrées** : ⌘-clic (Ctrl-clic sous Windows et Linux) ajoute une entrée à la sélection ou l'en retire ; ⇧-clic sélectionne toutes les lignes jusqu'à elle ; ⌘A (Ctrl+A) sélectionne toutes les lignes affichées. Les actions ci-dessous s'appliquent alors à toute la sélection.
46 - **Renommer** : survolez l'entrée et cliquez sur **✏️**, double-cliquez dessus, ou sélectionnez-la et appuyez sur **F2**. Tapez le nouveau nom, Entrée (Échap annule). Un fichier ouvert suit son nouveau nom, même avec des modifications non enregistrées.46 - **Renommer** : survolez l'entrée et cliquez sur **✏️**, double-cliquez dessus, ou sélectionnez-la et appuyez sur **F2**. Tapez le nouveau nom, Entrée (Échap annule). Un fichier ouvert suit son nouveau nom, même avec des modifications non enregistrées.
47 - **Déplacer** : glissez les entrées sur un dossier (ou sur un fichier, pour aller à côté ; sous les lignes pour la racine du dossier). Sans la souris : clic droit → **Move to…** et tapez le dossier (vide pour la racine). Un dossier ne va jamais dans lui-même, et rien ne remplace une entrée qui porte déjà ce nom.47 - **Déplacer** : glissez les entrées sur un dossier (ou sur un fichier, pour aller à côté ; sous les lignes pour la racine du dossier). Sans la souris : clic droit → **Move to…** et tapez le dossier (vide pour la racine). Un dossier ne va jamais dans lui-même, et rien ne remplace une entrée qui porte déjà ce nom.
48+- **Dupliquer** : clic droit → **Duplicate**, ou sélectionnez et appuyez sur ⌘D (Ctrl+D). La copie se place à côté de l'original, avec `-copy` avant l'extension (`plan.md` → `plan-copy.md`, puis `plan-copy-2.md`…) ; un dossier est copié avec son contenu. Un fichier protégé peut être dupliqué, et sa copie n'est pas protégée — sauf si elle tombe dans un dossier protégé, ce qui est refusé.
48 - **Clic droit** sur une entrée : un menu avec toutes ces actions, et **Afficher l'emplacement**.49 - **Clic droit** sur une entrée : un menu avec toutes ces actions, et **Afficher l'emplacement**.
49 - **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur, ou appuyez sur **Suppr** — ⌘⌫ sur Mac — dans l'arbre), puis confirmez ; avec plusieurs entrées sélectionnées, une seule confirmation suffit. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit.50 - **Supprimer** : survolez l'entrée et cliquez sur **🗑** (ou **Delete** sous l'éditeur, ou appuyez sur **Suppr** — ⌘⌫ sur Mac — dans l'arbre), puis confirmez ; avec plusieurs entrées sélectionnées, une seule confirmation suffit. Sur cet ordinateur, le fichier part à la corbeille — récupérez-le depuis le Finder si besoin. Dans un conteneur, la suppression est définitive, et la confirmation le dit.
50 51
modified docs/fr/reference/agents-et-evenements.md +1 -0
@@ -187,6 +187,7 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident
187187 | `RemoveAll(agent, paths)` | Supprime plusieurs fichiers et dossiers (un chemin à l'intérieur d'un autre de la liste est ignoré) ; rien n'est supprimé si l'un d'eux est protégé ou contient un fichier protégé. Issue #70. |
188188 | `Rename(agent, from, to)` | Renomme ou déplace un fichier ou un dossier vers le chemin `to` (ses dossiers sont créés) ; renvoie le nouveau chemin. Refusé si `to` existe, sort du dossier, est dans `from`, ou si `from` ou `to` est protégé. Issue #70. |
189189 | `Move(agent, paths, dir)` | Déplace des fichiers et dossiers dans `dir` (`""` est la racine), sans changer leur nom ; renvoie leurs nouveaux chemins. S'arrête au premier qui ne peut pas être déplacé. Issue #70. |
190+| `Duplicate(agent, paths)` | Copie des fichiers et dossiers à côté d'eux-mêmes, sous un nom libre avec `-copy` avant l'extension ; renvoie les chemins des copies. Une copie dont le chemin est protégé est refusée. Issue #70. |
190191 | `CreateFolder(agent, dir, name)` | Crée un dossier vide ; refusé si le nom existe ou contient `/`. Issue #70. |
191192 | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). |
192193 | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. |
@@ -187,6 +187,7 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident
187 | `RemoveAll(agent, paths)` | Supprime plusieurs fichiers et dossiers (un chemin à l'intérieur d'un autre de la liste est ignoré) ; rien n'est supprimé si l'un d'eux est protégé ou contient un fichier protégé. Issue #70. |187 | `RemoveAll(agent, paths)` | Supprime plusieurs fichiers et dossiers (un chemin à l'intérieur d'un autre de la liste est ignoré) ; rien n'est supprimé si l'un d'eux est protégé ou contient un fichier protégé. Issue #70. |
188 | `Rename(agent, from, to)` | Renomme ou déplace un fichier ou un dossier vers le chemin `to` (ses dossiers sont créés) ; renvoie le nouveau chemin. Refusé si `to` existe, sort du dossier, est dans `from`, ou si `from` ou `to` est protégé. Issue #70. |188 | `Rename(agent, from, to)` | Renomme ou déplace un fichier ou un dossier vers le chemin `to` (ses dossiers sont créés) ; renvoie le nouveau chemin. Refusé si `to` existe, sort du dossier, est dans `from`, ou si `from` ou `to` est protégé. Issue #70. |
189 | `Move(agent, paths, dir)` | Déplace des fichiers et dossiers dans `dir` (`""` est la racine), sans changer leur nom ; renvoie leurs nouveaux chemins. S'arrête au premier qui ne peut pas être déplacé. Issue #70. |189 | `Move(agent, paths, dir)` | Déplace des fichiers et dossiers dans `dir` (`""` est la racine), sans changer leur nom ; renvoie leurs nouveaux chemins. S'arrête au premier qui ne peut pas être déplacé. Issue #70. |
190+| `Duplicate(agent, paths)` | Copie des fichiers et dossiers à côté d'eux-mêmes, sous un nom libre avec `-copy` avant l'extension ; renvoie les chemins des copies. Une copie dont le chemin est protégé est refusée. Issue #70. |
190 | `CreateFolder(agent, dir, name)` | Crée un dossier vide ; refusé si le nom existe ou contient `/`. Issue #70. |191 | `CreateFolder(agent, dir, name)` | Crée un dossier vide ; refusé si le nom existe ou contient `/`. Issue #70. |
191 | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). |192 | `Attach(agent, hostPath)` | Joint un fichier de cet ordinateur à un message : renvoie son chemin dans le dossier de l'agent, à écrire après `$`. Un fichier déjà dans le dossier est utilisé sur place ; tout autre est copié dans `attachments/` (nom libre, espaces remplacés par `-`, 5 Mo au plus). |
192 | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. |193 | `ChooseAttachment()` | Affiche le sélecteur de fichier natif, depuis le dossier personnel ; renvoie le chemin choisi, ou `""`. |
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/workspaceservice.ts +11 -0
@@ -57,6 +57,17 @@ export function CreateFolder(agent: string, dir: string, name: string): $Cancell
5757 return $Call.ByID(3711526042, agent, dir, name);
5858 }
5959
60+/**
61+ * Duplicate copies files and folders next to themselves, under a free name
62+ * with "-copy" before the extension (plan.md → plan-copy.md, then
63+ * plan-copy-2.md…), and returns the paths of the copies (issue #70). A
64+ * protected file may be duplicated; a copy whose path would be protected is
65+ * refused. It stops at the first that cannot be copied.
66+ */
67+export function Duplicate(agent: string, files: string[] | null): $CancellablePromise<string[] | null> {
68+ return $Call.ByID(2054803095, agent, files);
69+}
70+
6071 /**
6172 * Image returns an image of the agent's folder as a data: URL, for the
6273 * preview of the image itself or of a document that shows it. Shown in an
@@ -57,6 +57,17 @@ export function CreateFolder(agent: string, dir: string, name: string): $Cancell
57 return $Call.ByID(3711526042, agent, dir, name);57 return $Call.ByID(3711526042, agent, dir, name);
58 }58 }
59 59
60+/**
61+ * Duplicate copies files and folders next to themselves, under a free name
62+ * with "-copy" before the extension (plan.md → plan-copy.md, then
63+ * plan-copy-2.md…), and returns the paths of the copies (issue #70). A
64+ * protected file may be duplicated; a copy whose path would be protected is
65+ * refused. It stops at the first that cannot be copied.
66+ */
67+export function Duplicate(agent: string, files: string[] | null): $CancellablePromise<string[] | null> {
68+ return $Call.ByID(2054803095, agent, files);
69+}
70+
60 /**71 /**
61 * Image returns an image of the agent's folder as a data: URL, for the72 * Image returns an image of the agent's folder as a data: URL, for the
62 * preview of the image itself or of a document that shows it. Shown in an73 * preview of the image itself or of a document that shows it. Shown in an
modified frontend/src/lib/agent/FilesTab.svelte +23 -1
@@ -272,6 +272,24 @@
272272 })
273273 }
274274
275+ // Copies the entry, or the selection it is part of, next to itself
276+ // (plan.md → plan-copy.md); the copies become the selection.
277+ async function duplicate(path: string) {
278+ menu = null
279+ const paths = selection.includes(path) ? [...selection] : [path]
280+ await attempt(async () => {
281+ try {
282+ const copies = (await WorkspaceService.Duplicate(agent, paths)) ?? []
283+ if (copies.length) {
284+ selection = copies
285+ selected = copies[copies.length - 1]
286+ }
287+ } finally {
288+ await refresh()
289+ }
290+ })
291+ }
292+
275293 function askMove(path: string) {
276294 menu = null
277295 moving = selection.includes(path) ? [...selection] : [path]
@@ -317,7 +335,7 @@
317335 menu = { x: event.clientX, y: event.clientY, path: entry.path }
318336 }
319337
320- // Shortcuts of the tree: F2 renames, Delete (⌘⌫ on a Mac) deletes, ⌘A
338+ // Shortcuts of the tree: F2 renames, ⌘D duplicates, Delete (⌘⌫ on a Mac) deletes, ⌘A
321339 // selects every row shown, Escape closes the menu or empties the selection.
322340 function treeKey(event: KeyboardEvent) {
323341 if ((event.target as HTMLElement).tagName === 'INPUT') return
@@ -328,6 +346,9 @@
328346 } else if ((event.key === 'Delete' || (event.key === 'Backspace' && mod)) && selection.length) {
329347 event.preventDefault()
330348 askRemove(selection[0])
349+ } else if (mod && event.key.toLowerCase() === 'd' && selection.length) {
350+ event.preventDefault()
351+ void duplicate(selection[0])
331352 } else if (mod && event.key.toLowerCase() === 'a') {
332353 event.preventDefault()
333354 selection = rows.map((row) => row.entry.path)
@@ -504,6 +525,7 @@
504525 {#if !blocked(targets)}
505526 <button role="menuitem" onclick={() => askMove(menu!.path)}>{many ? t('workspace.menu.moveMany', { count: targets.length }) : t('workspace.menu.move')}</button>
506527 {/if}
528+ <button role="menuitem" onclick={() => duplicate(menu!.path)}>{many ? t('workspace.menu.duplicateMany', { count: targets.length }) : t('workspace.menu.duplicate')}</button>
507529 {#if !many && revealable}
508530 <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; reveal(path) }}>📂 {t('linked.reveal')}</button>
509531 {/if}
@@ -272,6 +272,24 @@
272 })272 })
273 }273 }
274 274
275+ // Copies the entry, or the selection it is part of, next to itself
276+ // (plan.md → plan-copy.md); the copies become the selection.
277+ async function duplicate(path: string) {
278+ menu = null
279+ const paths = selection.includes(path) ? [...selection] : [path]
280+ await attempt(async () => {
281+ try {
282+ const copies = (await WorkspaceService.Duplicate(agent, paths)) ?? []
283+ if (copies.length) {
284+ selection = copies
285+ selected = copies[copies.length - 1]
286+ }
287+ } finally {
288+ await refresh()
289+ }
290+ })
291+ }
292+
275 function askMove(path: string) {293 function askMove(path: string) {
276 menu = null294 menu = null
277 moving = selection.includes(path) ? [...selection] : [path]295 moving = selection.includes(path) ? [...selection] : [path]
@@ -317,7 +335,7 @@
317 menu = { x: event.clientX, y: event.clientY, path: entry.path }335 menu = { x: event.clientX, y: event.clientY, path: entry.path }
318 }336 }
319 337
320- // Shortcuts of the tree: F2 renames, Delete (⌘⌫ on a Mac) deletes, ⌘A338+ // Shortcuts of the tree: F2 renames, ⌘D duplicates, Delete (⌘⌫ on a Mac) deletes, ⌘A
321 // selects every row shown, Escape closes the menu or empties the selection.339 // selects every row shown, Escape closes the menu or empties the selection.
322 function treeKey(event: KeyboardEvent) {340 function treeKey(event: KeyboardEvent) {
323 if ((event.target as HTMLElement).tagName === 'INPUT') return341 if ((event.target as HTMLElement).tagName === 'INPUT') return
@@ -328,6 +346,9 @@
328 } else if ((event.key === 'Delete' || (event.key === 'Backspace' && mod)) && selection.length) {346 } else if ((event.key === 'Delete' || (event.key === 'Backspace' && mod)) && selection.length) {
329 event.preventDefault()347 event.preventDefault()
330 askRemove(selection[0])348 askRemove(selection[0])
349+ } else if (mod && event.key.toLowerCase() === 'd' && selection.length) {
350+ event.preventDefault()
351+ void duplicate(selection[0])
331 } else if (mod && event.key.toLowerCase() === 'a') {352 } else if (mod && event.key.toLowerCase() === 'a') {
332 event.preventDefault()353 event.preventDefault()
333 selection = rows.map((row) => row.entry.path)354 selection = rows.map((row) => row.entry.path)
@@ -504,6 +525,7 @@
504 {#if !blocked(targets)}525 {#if !blocked(targets)}
505 <button role="menuitem" onclick={() => askMove(menu!.path)}>{many ? t('workspace.menu.moveMany', { count: targets.length }) : t('workspace.menu.move')}</button>526 <button role="menuitem" onclick={() => askMove(menu!.path)}>{many ? t('workspace.menu.moveMany', { count: targets.length }) : t('workspace.menu.move')}</button>
506 {/if}527 {/if}
528+ <button role="menuitem" onclick={() => duplicate(menu!.path)}>{many ? t('workspace.menu.duplicateMany', { count: targets.length }) : t('workspace.menu.duplicate')}</button>
507 {#if !many && revealable}529 {#if !many && revealable}
508 <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; reveal(path) }}>📂 {t('linked.reveal')}</button>530 <button role="menuitem" onclick={() => { const path = menu!.path; menu = null; reveal(path) }}>📂 {t('linked.reveal')}</button>
509 {/if}531 {/if}
modified frontend/src/lib/i18n/messages.ts +4 -0
@@ -262,6 +262,8 @@ export const en = {
262262 'workspace.menu.move': 'Move to…',
263263 'workspace.menu.moveMany': 'Move {count} items to…',
264264 'workspace.menu.deleteMany': 'Delete {count} items',
265+ 'workspace.menu.duplicate': 'Duplicate (⌘D)',
266+ 'workspace.menu.duplicateMany': 'Duplicate {count} items (⌘D)',
265267 'workspace.newFileIn': 'New file in {folder}',
266268 'workspace.fileName': 'File name',
267269 'workspace.create': 'Create',
@@ -634,6 +636,8 @@ export const fr: Record<MessageKey, string> = {
634636 'workspace.menu.move': 'Déplacer vers…',
635637 'workspace.menu.moveMany': 'Déplacer {count} éléments vers…',
636638 'workspace.menu.deleteMany': 'Supprimer {count} éléments',
639+ 'workspace.menu.duplicate': 'Dupliquer (⌘D)',
640+ 'workspace.menu.duplicateMany': 'Dupliquer {count} éléments (⌘D)',
637641 'workspace.newFileIn': 'Nouveau fichier dans {folder}',
638642 'workspace.fileName': 'Nom du fichier',
639643 'workspace.create': 'Créer',
@@ -262,6 +262,8 @@ export const en = {
262 'workspace.menu.move': 'Move to…',262 'workspace.menu.move': 'Move to…',
263 'workspace.menu.moveMany': 'Move {count} items to…',263 'workspace.menu.moveMany': 'Move {count} items to…',
264 'workspace.menu.deleteMany': 'Delete {count} items',264 'workspace.menu.deleteMany': 'Delete {count} items',
265+ 'workspace.menu.duplicate': 'Duplicate (⌘D)',
266+ 'workspace.menu.duplicateMany': 'Duplicate {count} items (⌘D)',
265 'workspace.newFileIn': 'New file in {folder}',267 'workspace.newFileIn': 'New file in {folder}',
266 'workspace.fileName': 'File name',268 'workspace.fileName': 'File name',
267 'workspace.create': 'Create',269 'workspace.create': 'Create',
@@ -634,6 +636,8 @@ export const fr: Record<MessageKey, string> = {
634 'workspace.menu.move': 'Déplacer vers…',636 'workspace.menu.move': 'Déplacer vers…',
635 'workspace.menu.moveMany': 'Déplacer {count} éléments vers…',637 'workspace.menu.moveMany': 'Déplacer {count} éléments vers…',
636 'workspace.menu.deleteMany': 'Supprimer {count} éléments',638 'workspace.menu.deleteMany': 'Supprimer {count} éléments',
639+ 'workspace.menu.duplicate': 'Dupliquer (⌘D)',
640+ 'workspace.menu.duplicateMany': 'Dupliquer {count} éléments (⌘D)',
637 'workspace.newFileIn': 'Nouveau fichier dans {folder}',641 'workspace.newFileIn': 'Nouveau fichier dans {folder}',
638 'workspace.fileName': 'Nom du fichier',642 'workspace.fileName': 'Nom du fichier',
639 'workspace.create': 'Créer',643 'workspace.create': 'Créer',
modified internal/app/app_test.go +24 -0
@@ -428,6 +428,30 @@ func TestTheWorkspaceServiceRenamesMovesAndRemovesSeveralFiles(t *testing.T) {
428428 }
429429 }
430430
431+func TestTheWorkspaceServiceDuplicatesFilesAndFolders(t *testing.T) {
432+ core, folder, _ := workspaceCore(t)
433+ service := &app.WorkspaceService{Core: core}
434+ ctx := context.Background()
435+ if err := os.MkdirAll(filepath.Join(folder, "archive"), 0o755); err != nil {
436+ t.Fatal(err)
437+ }
438+ write(t, filepath.Join(folder, "archive", "plan.md"), "plan")
439+ copies, err := service.Duplicate(ctx, "alice", []string{"archive/plan.md", "archive"})
440+ if err != nil || strings.Join(copies, ",") != "archive-copy" {
441+ t.Fatalf("a file inside a duplicated folder is not copied twice: %v %v", copies, err)
442+ }
443+ copies, err = service.Duplicate(ctx, "alice", []string{"archive/plan.md"})
444+ if err != nil || copies[0] != "archive/plan-copy.md" {
445+ t.Fatalf("duplicate: %v %v", copies, err)
446+ }
447+ if copies, err = service.Duplicate(ctx, "alice", []string{"archive/plan.md"}); err != nil || copies[0] != "archive/plan-copy-2.md" {
448+ t.Fatalf("the next copy takes a free name: %v %v", copies, err)
449+ }
450+ if content, _ := os.ReadFile(filepath.Join(folder, "archive-copy", "plan.md")); string(content) != "plan" {
451+ t.Fatalf("the folder is copied with its content: %q", content)
452+ }
453+}
454+
431455 func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) {
432456 core, folder, recorder := workspaceCore(t)
433457 service := &app.WorkspaceService{Core: core}
@@ -428,6 +428,30 @@ func TestTheWorkspaceServiceRenamesMovesAndRemovesSeveralFiles(t *testing.T) {
428 }428 }
429 }429 }
430 430
431+func TestTheWorkspaceServiceDuplicatesFilesAndFolders(t *testing.T) {
432+ core, folder, _ := workspaceCore(t)
433+ service := &app.WorkspaceService{Core: core}
434+ ctx := context.Background()
435+ if err := os.MkdirAll(filepath.Join(folder, "archive"), 0o755); err != nil {
436+ t.Fatal(err)
437+ }
438+ write(t, filepath.Join(folder, "archive", "plan.md"), "plan")
439+ copies, err := service.Duplicate(ctx, "alice", []string{"archive/plan.md", "archive"})
440+ if err != nil || strings.Join(copies, ",") != "archive-copy" {
441+ t.Fatalf("a file inside a duplicated folder is not copied twice: %v %v", copies, err)
442+ }
443+ copies, err = service.Duplicate(ctx, "alice", []string{"archive/plan.md"})
444+ if err != nil || copies[0] != "archive/plan-copy.md" {
445+ t.Fatalf("duplicate: %v %v", copies, err)
446+ }
447+ if copies, err = service.Duplicate(ctx, "alice", []string{"archive/plan.md"}); err != nil || copies[0] != "archive/plan-copy-2.md" {
448+ t.Fatalf("the next copy takes a free name: %v %v", copies, err)
449+ }
450+ if content, _ := os.ReadFile(filepath.Join(folder, "archive-copy", "plan.md")); string(content) != "plan" {
451+ t.Fatalf("the folder is copied with its content: %q", content)
452+ }
453+}
454+
431 func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) {455 func TestWatchAnnouncesChangesUntilUnwatch(t *testing.T) {
432 core, folder, recorder := workspaceCore(t)456 core, folder, recorder := workspaceCore(t)
433 service := &app.WorkspaceService{Core: core}457 service := &app.WorkspaceService{Core: core}
modified internal/app/protect_test.go +6 -0
@@ -98,6 +98,12 @@ func TestProtectedFilesCannotBeRenamedMovedNorRemovedTogether(t *testing.T) {
9898 if _, err := service.Move(ctx, "bob", []string{"agent.yaml"}, "archive"); !errors.Is(err, workspace.ErrProtected) {
9999 t.Fatalf("moving a protected file is refused: %v", err)
100100 }
101+ if copies, err := service.Duplicate(ctx, "bob", []string{"AGENTS.md"}); err != nil || copies[0] != "AGENTS-copy.md" {
102+ t.Fatalf("a protected file may be duplicated, its copy is not protected: %v %v", copies, err)
103+ }
104+ if _, err := service.Duplicate(ctx, "bob", []string{"skills/idioms/SKILL.md"}); !errors.Is(err, workspace.ErrProtected) {
105+ t.Fatalf("a copy inside a protected folder is refused: %v", err)
106+ }
101107 if err := service.RemoveAll(ctx, "bob", []string{"notes.md", "AGENTS.md"}); !errors.Is(err, workspace.ErrProtected) {
102108 t.Fatalf("removing a protected file with others is refused: %v", err)
103109 }
@@ -98,6 +98,12 @@ func TestProtectedFilesCannotBeRenamedMovedNorRemovedTogether(t *testing.T) {
98 if _, err := service.Move(ctx, "bob", []string{"agent.yaml"}, "archive"); !errors.Is(err, workspace.ErrProtected) {98 if _, err := service.Move(ctx, "bob", []string{"agent.yaml"}, "archive"); !errors.Is(err, workspace.ErrProtected) {
99 t.Fatalf("moving a protected file is refused: %v", err)99 t.Fatalf("moving a protected file is refused: %v", err)
100 }100 }
101+ if copies, err := service.Duplicate(ctx, "bob", []string{"AGENTS.md"}); err != nil || copies[0] != "AGENTS-copy.md" {
102+ t.Fatalf("a protected file may be duplicated, its copy is not protected: %v %v", copies, err)
103+ }
104+ if _, err := service.Duplicate(ctx, "bob", []string{"skills/idioms/SKILL.md"}); !errors.Is(err, workspace.ErrProtected) {
105+ t.Fatalf("a copy inside a protected folder is refused: %v", err)
106+ }
101 if err := service.RemoveAll(ctx, "bob", []string{"notes.md", "AGENTS.md"}); !errors.Is(err, workspace.ErrProtected) {107 if err := service.RemoveAll(ctx, "bob", []string{"notes.md", "AGENTS.md"}); !errors.Is(err, workspace.ErrProtected) {
102 t.Fatalf("removing a protected file with others is refused: %v", err)108 t.Fatalf("removing a protected file with others is refused: %v", err)
103 }109 }
modified internal/app/workspaces.go +45 -0
@@ -240,6 +240,51 @@ func (s *WorkspaceService) Move(ctx context.Context, agent string, files []strin
240240 return moved, nil
241241 }
242242
243+// Duplicate copies files and folders next to themselves, under a free name
244+// with "-copy" before the extension (plan.md → plan-copy.md, then
245+// plan-copy-2.md…), and returns the paths of the copies (issue #70). A
246+// protected file may be duplicated; a copy whose path would be protected is
247+// refused. It stops at the first that cannot be copied.
248+func (s *WorkspaceService) Duplicate(ctx context.Context, agent string, files []string) ([]string, error) {
249+ ws, err := s.Core.workspaceOf(agent)
250+ if err != nil {
251+ return nil, err
252+ }
253+ outermost, err := workspace.Outermost(files)
254+ if err != nil {
255+ return nil, err
256+ }
257+ protection := s.Core.protectionOf(agent)
258+ copies := []string{}
259+ for _, file := range outermost {
260+ if file == "" {
261+ return copies, workspace.ErrOutside // never the whole folder
262+ }
263+ parent := path.Dir(file)
264+ if parent == "." {
265+ parent = ""
266+ }
267+ entries, err := ws.List(ctx, parent)
268+ if err != nil {
269+ return copies, fmt.Errorf("%s: %w", file, err)
270+ }
271+ taken := map[string]bool{}
272+ for _, entry := range entries {
273+ taken[entry.Name] = true
274+ }
275+ name := workspace.FreeName(workspace.CopyName(path.Base(file)), func(candidate string) bool { return taken[candidate] })
276+ target := path.Join(parent, name)
277+ if protection.Protects(target) {
278+ return copies, fmt.Errorf("%s: %w", target, workspace.ErrProtected)
279+ }
280+ if err := ws.Copy(ctx, file, target); err != nil {
281+ return copies, fmt.Errorf("%s: %w", file, err)
282+ }
283+ copies = append(copies, target)
284+ }
285+ return copies, nil
286+}
287+
243288 // CreateFolder creates an empty folder called name in folder dir and
244289 // returns its path (issue #70).
245290 func (s *WorkspaceService) CreateFolder(ctx context.Context, agent, dir, name string) (string, error) {
@@ -240,6 +240,51 @@ func (s *WorkspaceService) Move(ctx context.Context, agent string, files []strin
240 return moved, nil240 return moved, nil
241 }241 }
242 242
243+// Duplicate copies files and folders next to themselves, under a free name
244+// with "-copy" before the extension (plan.md → plan-copy.md, then
245+// plan-copy-2.md…), and returns the paths of the copies (issue #70). A
246+// protected file may be duplicated; a copy whose path would be protected is
247+// refused. It stops at the first that cannot be copied.
248+func (s *WorkspaceService) Duplicate(ctx context.Context, agent string, files []string) ([]string, error) {
249+ ws, err := s.Core.workspaceOf(agent)
250+ if err != nil {
251+ return nil, err
252+ }
253+ outermost, err := workspace.Outermost(files)
254+ if err != nil {
255+ return nil, err
256+ }
257+ protection := s.Core.protectionOf(agent)
258+ copies := []string{}
259+ for _, file := range outermost {
260+ if file == "" {
261+ return copies, workspace.ErrOutside // never the whole folder
262+ }
263+ parent := path.Dir(file)
264+ if parent == "." {
265+ parent = ""
266+ }
267+ entries, err := ws.List(ctx, parent)
268+ if err != nil {
269+ return copies, fmt.Errorf("%s: %w", file, err)
270+ }
271+ taken := map[string]bool{}
272+ for _, entry := range entries {
273+ taken[entry.Name] = true
274+ }
275+ name := workspace.FreeName(workspace.CopyName(path.Base(file)), func(candidate string) bool { return taken[candidate] })
276+ target := path.Join(parent, name)
277+ if protection.Protects(target) {
278+ return copies, fmt.Errorf("%s: %w", target, workspace.ErrProtected)
279+ }
280+ if err := ws.Copy(ctx, file, target); err != nil {
281+ return copies, fmt.Errorf("%s: %w", file, err)
282+ }
283+ copies = append(copies, target)
284+ }
285+ return copies, nil
286+}
287+
243 // CreateFolder creates an empty folder called name in folder dir and288 // CreateFolder creates an empty folder called name in folder dir and
244 // returns its path (issue #70).289 // returns its path (issue #70).
245 func (s *WorkspaceService) CreateFolder(ctx context.Context, agent, dir, name string) (string, error) {290 func (s *WorkspaceService) CreateFolder(ctx context.Context, agent, dir, name string) (string, error) {
modified internal/workspace/container.go +20 -0
@@ -261,6 +261,26 @@ mkdir -p "$(dirname "$2")" && mv -- "$1" "$2"`
261261 return err
262262 }
263263
264+// Copy implements Workspace.
265+func (c *Remote) Copy(ctx context.Context, from, to string) error {
266+ source, fromRel, err := c.resolve(from)
267+ if err != nil {
268+ return err
269+ }
270+ target, toRel, err := c.resolve(to)
271+ if err != nil {
272+ return err
273+ }
274+ if err := checkRename(fromRel, toRel); err != nil {
275+ return err
276+ }
277+ const script = `test -e "$1" || test -L "$1" || exit 3
278+if test -e "$2" || test -L "$2"; then exit 5; fi
279+mkdir -p "$(dirname "$2")" && cp -RPp -- "$1" "$2"`
280+ _, err = c.run(ctx, script, source, nil, target)
281+ return err
282+}
283+
264284 // MakeDir implements Workspace.
265285 func (c *Remote) MakeDir(ctx context.Context, p string) error {
266286 abs, rel, err := c.resolve(p)
@@ -261,6 +261,26 @@ mkdir -p "$(dirname "$2")" && mv -- "$1" "$2"`
261 return err261 return err
262 }262 }
263 263
264+// Copy implements Workspace.
265+func (c *Remote) Copy(ctx context.Context, from, to string) error {
266+ source, fromRel, err := c.resolve(from)
267+ if err != nil {
268+ return err
269+ }
270+ target, toRel, err := c.resolve(to)
271+ if err != nil {
272+ return err
273+ }
274+ if err := checkRename(fromRel, toRel); err != nil {
275+ return err
276+ }
277+ const script = `test -e "$1" || test -L "$1" || exit 3
278+if test -e "$2" || test -L "$2"; then exit 5; fi
279+mkdir -p "$(dirname "$2")" && cp -RPp -- "$1" "$2"`
280+ _, err = c.run(ctx, script, source, nil, target)
281+ return err
282+}
283+
264 // MakeDir implements Workspace.284 // MakeDir implements Workspace.
265 func (c *Remote) MakeDir(ctx context.Context, p string) error {285 func (c *Remote) MakeDir(ctx context.Context, p string) error {
266 abs, rel, err := c.resolve(p)286 abs, rel, err := c.resolve(p)
modified internal/workspace/contract_test.go +39 -0
@@ -130,6 +130,7 @@ func contract(t *testing.T, open opener) {
130130 {"removes a file and a folder", checkRemovesAFileAndAFolder},
131131 {"renames and moves files and folders", checkRenamesAndMovesFilesAndFolders},
132132 {"creates a folder", checkCreatesAFolder},
133+ {"copies files and folders", checkCopiesFilesAndFolders},
133134 {"signals changes", checkSignalsChanges},
134135 {"opens a shell in the folder", checkOpensAShellInTheFolder},
135136 {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt},
@@ -320,6 +321,36 @@ func checkRenamesAndMovesFilesAndFolders(t *testing.T, open opener) {
320321 }
321322 }
322323
324+func checkCopiesFilesAndFolders(t *testing.T, open opener) {
325+ ctx := context.Background()
326+ ws := startWorkspace(t, open)
327+ if err := ws.Copy(ctx, "AGENTS.md", "AGENTS-copy.md"); err != nil {
328+ t.Fatal(err)
329+ }
330+ for _, name := range []string{"AGENTS.md", "AGENTS-copy.md"} {
331+ if file, err := ws.Read(ctx, name); err != nil || file.Content != "# Style\n" {
332+ t.Fatalf("%s: %+v %v", name, file, err)
333+ }
334+ }
335+ if err := ws.Copy(ctx, "skills", "archive/skills"); err != nil {
336+ t.Fatal(err)
337+ }
338+ for _, name := range []string{"skills/idioms/SKILL.md", "archive/skills/idioms/SKILL.md"} {
339+ if file, err := ws.Read(ctx, name); err != nil || file.Content != "idioms" {
340+ t.Fatalf("%s: %+v %v", name, file, err)
341+ }
342+ }
343+ if err := ws.Copy(ctx, "AGENTS.md", "notes"); !errors.Is(err, workspace.ErrExists) {
344+ t.Fatalf("never over an existing entry, got %v", err)
345+ }
346+ if err := ws.Copy(ctx, "missing.md", "found.md"); !errors.Is(err, workspace.ErrNotFound) {
347+ t.Fatalf("want ErrNotFound, got %v", err)
348+ }
349+ if err := ws.Copy(ctx, "skills", "skills/inside"); err == nil {
350+ t.Fatal("a folder cannot be copied inside itself")
351+ }
352+}
353+
323354 func checkCreatesAFolder(t *testing.T, open opener) {
324355 ctx := context.Background()
325356 ws := startWorkspace(t, open)
@@ -518,6 +549,14 @@ func TestOutermostKeepsWhatIsNotInsideAnotherPath(t *testing.T) {
518549 }
519550 }
520551
552+func TestCopyNameAddsCopyBeforeTheExtension(t *testing.T) {
553+ for name, want := range map[string]string{"plan.md": "plan-copy.md", ".env": ".env-copy", "notes": "notes-copy", "a.tar.gz": "a.tar-copy.gz"} {
554+ if got := workspace.CopyName(name); got != want {
555+ t.Errorf("CopyName(%q) = %q, want %q", name, got, want)
556+ }
557+ }
558+}
559+
521560 func ExampleClean() {
522561 cleaned, _ := workspace.Clean("skills/../AGENTS.md")
523562 _, err := workspace.Clean("../secrets")
@@ -130,6 +130,7 @@ func contract(t *testing.T, open opener) {
130 {"removes a file and a folder", checkRemovesAFileAndAFolder},130 {"removes a file and a folder", checkRemovesAFileAndAFolder},
131 {"renames and moves files and folders", checkRenamesAndMovesFilesAndFolders},131 {"renames and moves files and folders", checkRenamesAndMovesFilesAndFolders},
132 {"creates a folder", checkCreatesAFolder},132 {"creates a folder", checkCreatesAFolder},
133+ {"copies files and folders", checkCopiesFilesAndFolders},
133 {"signals changes", checkSignalsChanges},134 {"signals changes", checkSignalsChanges},
134 {"opens a shell in the folder", checkOpensAShellInTheFolder},135 {"opens a shell in the folder", checkOpensAShellInTheFolder},
135 {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt},136 {"a shell exits even when nobody reads it", checkAShellExitsEvenWhenNobodyReadsIt},
@@ -320,6 +321,36 @@ func checkRenamesAndMovesFilesAndFolders(t *testing.T, open opener) {
320 }321 }
321 }322 }
322 323
324+func checkCopiesFilesAndFolders(t *testing.T, open opener) {
325+ ctx := context.Background()
326+ ws := startWorkspace(t, open)
327+ if err := ws.Copy(ctx, "AGENTS.md", "AGENTS-copy.md"); err != nil {
328+ t.Fatal(err)
329+ }
330+ for _, name := range []string{"AGENTS.md", "AGENTS-copy.md"} {
331+ if file, err := ws.Read(ctx, name); err != nil || file.Content != "# Style\n" {
332+ t.Fatalf("%s: %+v %v", name, file, err)
333+ }
334+ }
335+ if err := ws.Copy(ctx, "skills", "archive/skills"); err != nil {
336+ t.Fatal(err)
337+ }
338+ for _, name := range []string{"skills/idioms/SKILL.md", "archive/skills/idioms/SKILL.md"} {
339+ if file, err := ws.Read(ctx, name); err != nil || file.Content != "idioms" {
340+ t.Fatalf("%s: %+v %v", name, file, err)
341+ }
342+ }
343+ if err := ws.Copy(ctx, "AGENTS.md", "notes"); !errors.Is(err, workspace.ErrExists) {
344+ t.Fatalf("never over an existing entry, got %v", err)
345+ }
346+ if err := ws.Copy(ctx, "missing.md", "found.md"); !errors.Is(err, workspace.ErrNotFound) {
347+ t.Fatalf("want ErrNotFound, got %v", err)
348+ }
349+ if err := ws.Copy(ctx, "skills", "skills/inside"); err == nil {
350+ t.Fatal("a folder cannot be copied inside itself")
351+ }
352+}
353+
323 func checkCreatesAFolder(t *testing.T, open opener) {354 func checkCreatesAFolder(t *testing.T, open opener) {
324 ctx := context.Background()355 ctx := context.Background()
325 ws := startWorkspace(t, open)356 ws := startWorkspace(t, open)
@@ -518,6 +549,14 @@ func TestOutermostKeepsWhatIsNotInsideAnotherPath(t *testing.T) {
518 }549 }
519 }550 }
520 551
552+func TestCopyNameAddsCopyBeforeTheExtension(t *testing.T) {
553+ for name, want := range map[string]string{"plan.md": "plan-copy.md", ".env": ".env-copy", "notes": "notes-copy", "a.tar.gz": "a.tar-copy.gz"} {
554+ if got := workspace.CopyName(name); got != want {
555+ t.Errorf("CopyName(%q) = %q, want %q", name, got, want)
556+ }
557+ }
558+}
559+
521 func ExampleClean() {560 func ExampleClean() {
522 cleaned, _ := workspace.Clean("skills/../AGENTS.md")561 cleaned, _ := workspace.Clean("skills/../AGENTS.md")
523 _, err := workspace.Clean("../secrets")562 _, err := workspace.Clean("../secrets")
modified internal/workspace/local.go +70 -0
@@ -5,6 +5,7 @@ package workspace
55 import (
66 "context"
77 "errors"
8+ "io"
89 "io/fs"
910 "os"
1011 "os/exec"
@@ -252,6 +253,75 @@ func (l *Local) Rename(_ context.Context, from, to string) error {
252253 return os.Rename(source, target)
253254 }
254255
256+// Copy implements Workspace: files keep their permissions, symbolic links
257+// are copied as links.
258+func (l *Local) Copy(_ context.Context, from, to string) error {
259+ source, fromRel, err := l.resolve(from)
260+ if err != nil {
261+ return err
262+ }
263+ target, toRel, err := l.resolve(to)
264+ if err != nil {
265+ return err
266+ }
267+ if err := checkRename(fromRel, toRel); err != nil {
268+ return err
269+ }
270+ if _, err := os.Lstat(source); err != nil {
271+ return notFound(err)
272+ }
273+ if _, err := os.Lstat(target); err == nil {
274+ return ErrExists
275+ }
276+ return filepath.WalkDir(source, func(p string, entry fs.DirEntry, err error) error {
277+ if err != nil {
278+ return err
279+ }
280+ rel, err := filepath.Rel(source, p)
281+ if err != nil {
282+ return err
283+ }
284+ destination := filepath.Join(target, rel)
285+ info, err := entry.Info()
286+ if err != nil {
287+ return err
288+ }
289+ switch {
290+ case entry.Type()&fs.ModeSymlink != 0:
291+ link, err := os.Readlink(p)
292+ if err != nil {
293+ return err
294+ }
295+ return os.Symlink(link, destination)
296+ case entry.IsDir():
297+ return os.MkdirAll(destination, info.Mode().Perm()|0o700)
298+ default:
299+ return copyFile(p, destination, info.Mode().Perm())
300+ }
301+ })
302+}
303+
304+// copyFile copies the file at source to destination, which must not exist.
305+func copyFile(source, destination string, mode fs.FileMode) error {
306+ if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
307+ return err
308+ }
309+ in, err := os.Open(source)
310+ if err != nil {
311+ return err
312+ }
313+ defer func() { _ = in.Close() }()
314+ out, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
315+ if err != nil {
316+ return err
317+ }
318+ if _, err := io.Copy(out, in); err != nil {
319+ _ = out.Close()
320+ return err
321+ }
322+ return out.Close()
323+}
324+
255325 // MakeDir implements Workspace.
256326 func (l *Local) MakeDir(_ context.Context, p string) error {
257327 abs, rel, err := l.resolve(p)
@@ -5,6 +5,7 @@ package workspace
5 import (5 import (
6 "context"6 "context"
7 "errors"7 "errors"
8+ "io"
8 "io/fs"9 "io/fs"
9 "os"10 "os"
10 "os/exec"11 "os/exec"
@@ -252,6 +253,75 @@ func (l *Local) Rename(_ context.Context, from, to string) error {
252 return os.Rename(source, target)253 return os.Rename(source, target)
253 }254 }
254 255
256+// Copy implements Workspace: files keep their permissions, symbolic links
257+// are copied as links.
258+func (l *Local) Copy(_ context.Context, from, to string) error {
259+ source, fromRel, err := l.resolve(from)
260+ if err != nil {
261+ return err
262+ }
263+ target, toRel, err := l.resolve(to)
264+ if err != nil {
265+ return err
266+ }
267+ if err := checkRename(fromRel, toRel); err != nil {
268+ return err
269+ }
270+ if _, err := os.Lstat(source); err != nil {
271+ return notFound(err)
272+ }
273+ if _, err := os.Lstat(target); err == nil {
274+ return ErrExists
275+ }
276+ return filepath.WalkDir(source, func(p string, entry fs.DirEntry, err error) error {
277+ if err != nil {
278+ return err
279+ }
280+ rel, err := filepath.Rel(source, p)
281+ if err != nil {
282+ return err
283+ }
284+ destination := filepath.Join(target, rel)
285+ info, err := entry.Info()
286+ if err != nil {
287+ return err
288+ }
289+ switch {
290+ case entry.Type()&fs.ModeSymlink != 0:
291+ link, err := os.Readlink(p)
292+ if err != nil {
293+ return err
294+ }
295+ return os.Symlink(link, destination)
296+ case entry.IsDir():
297+ return os.MkdirAll(destination, info.Mode().Perm()|0o700)
298+ default:
299+ return copyFile(p, destination, info.Mode().Perm())
300+ }
301+ })
302+}
303+
304+// copyFile copies the file at source to destination, which must not exist.
305+func copyFile(source, destination string, mode fs.FileMode) error {
306+ if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
307+ return err
308+ }
309+ in, err := os.Open(source)
310+ if err != nil {
311+ return err
312+ }
313+ defer func() { _ = in.Close() }()
314+ out, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
315+ if err != nil {
316+ return err
317+ }
318+ if _, err := io.Copy(out, in); err != nil {
319+ _ = out.Close()
320+ return err
321+ }
322+ return out.Close()
323+}
324+
255 // MakeDir implements Workspace.325 // MakeDir implements Workspace.
256 func (l *Local) MakeDir(_ context.Context, p string) error {326 func (l *Local) MakeDir(_ context.Context, p string) error {
257 abs, rel, err := l.resolve(p)327 abs, rel, err := l.resolve(p)
modified internal/workspace/workspace.go +25 -0
@@ -110,6 +110,10 @@ type Workspace interface {
110110 // created if needed); ErrExists when something already has that path
111111 // (issue #70).
112112 Rename(ctx context.Context, from, to string) error
113+ // Copy copies a file, or a folder with its content, to path to (its
114+ // folders are created if needed); ErrExists when something already has
115+ // that path (issue #70).
116+ Copy(ctx context.Context, from, to string) error
113117 // MakeDir creates a folder, and its parents if needed; ErrExists when
114118 // something already has that path (issue #70).
115119 MakeDir(ctx context.Context, path string) error
@@ -214,6 +218,27 @@ func Outermost(paths []string) ([]string, error) {
214218 return result, nil
215219 }
216220
221+// CopyName is the name of the copy of name: "-copy" before its extension.
222+//
223+// CopyName("plan.md") // "plan-copy.md"
224+// CopyName(".env") // ".env-copy"
225+func CopyName(name string) string {
226+ extension := path.Ext(name)
227+ base := strings.TrimSuffix(name, extension)
228+ if base == "" {
229+ base, extension = name, ""
230+ }
231+ return base + "-copy" + extension
232+}
233+
234+// FreeName returns name, or name with -2, -3… before its extension, the
235+// first one taken does not take.
236+//
237+// FreeName("plan-copy.md", taken) // "plan-copy.md", then "plan-copy-2.md"…
238+func FreeName(name string, taken func(string) bool) string {
239+ return freeName(name, taken)
240+}
241+
217242 // checkImport checks the name and the size of an imported file.
218243 func checkImport(name string, data []byte) error {
219244 if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") {
@@ -110,6 +110,10 @@ type Workspace interface {
110 // created if needed); ErrExists when something already has that path110 // created if needed); ErrExists when something already has that path
111 // (issue #70).111 // (issue #70).
112 Rename(ctx context.Context, from, to string) error112 Rename(ctx context.Context, from, to string) error
113+ // Copy copies a file, or a folder with its content, to path to (its
114+ // folders are created if needed); ErrExists when something already has
115+ // that path (issue #70).
116+ Copy(ctx context.Context, from, to string) error
113 // MakeDir creates a folder, and its parents if needed; ErrExists when117 // MakeDir creates a folder, and its parents if needed; ErrExists when
114 // something already has that path (issue #70).118 // something already has that path (issue #70).
115 MakeDir(ctx context.Context, path string) error119 MakeDir(ctx context.Context, path string) error
@@ -214,6 +218,27 @@ func Outermost(paths []string) ([]string, error) {
214 return result, nil218 return result, nil
215 }219 }
216 220
221+// CopyName is the name of the copy of name: "-copy" before its extension.
222+//
223+// CopyName("plan.md") // "plan-copy.md"
224+// CopyName(".env") // ".env-copy"
225+func CopyName(name string) string {
226+ extension := path.Ext(name)
227+ base := strings.TrimSuffix(name, extension)
228+ if base == "" {
229+ base, extension = name, ""
230+ }
231+ return base + "-copy" + extension
232+}
233+
234+// FreeName returns name, or name with -2, -3… before its extension, the
235+// first one taken does not take.
236+//
237+// FreeName("plan-copy.md", taken) // "plan-copy.md", then "plan-copy-2.md"…
238+func FreeName(name string, taken func(string) bool) string {
239+ return freeName(name, taken)
240+}
241+
217 // checkImport checks the name and the size of an imported file.242 // checkImport checks the name and the size of an imported file.
218 func checkImport(name string, data []byte) error {243 func checkImport(name string, data []byte) error {
219 if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") {244 if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") {