@@ -18,7 +18,7 @@ import {
1818import type { SessionID } from "@opencode/schema/session-id"
1919import { Global } from "@opencode/util/global"
2020import { makeLocationNode } from "@opencode/util/effect/app-node"
21- import { Clock , Context , Effect , Layer , Option , Schema } from "effect"
21+ import { Clock , Context , Effect , Layer , Option , Schema , Semaphore } from "effect"
2222import { Bus } from "./bus.js"
2323import { Flag } from "./flag.js"
2424import { KV } from "./kv.js"
@@ -200,6 +200,18 @@ export const locate = (kv: KV.Interface, id: ID) =>
200200 } ) ,
201201 )
202202
203+ // The artifact service is location-scoped while artifact directories are global, so one lock per artifact
204+ // is shared by every location in this process. It serializes directory swaps so two writes cannot move the
205+ // same directory out from under each other.
206+ const writeLocks = new Map < ID , Semaphore . Semaphore > ( )
207+ const lockFor = ( id : ID ) => {
208+ const current = writeLocks . get ( id )
209+ if ( current ) return current
210+ const created = Semaphore . makeUnsafe ( 1 )
211+ writeLocks . set ( id , created )
212+ return created
213+ }
214+
203215const layer = Layer . effect (
204216 Service ,
205217 Effect . gen ( function * ( ) {
@@ -226,10 +238,16 @@ const layer = Layer.effect(
226238 prompt :
227239 "Artifacts are served as HTML by this OpenCode server. Only people who can reach this server can open them." ,
228240 create : ( input ) =>
229- replaceDirectoryFiles ( itemDir ( input . id ) , input . files ) . pipe ( Effect . as ( { url : viewURL ( input . id ) } ) ) ,
230- read : ( id ) => readDirectoryFiles ( itemDir ( id ) ) ,
231- update : ( id , input ) => replaceDirectoryFiles ( itemDir ( id ) , input . files ) . pipe ( Effect . as ( { url : viewURL ( id ) } ) ) ,
232- delete : ( id ) => Effect . promise ( ( ) => fs . rm ( itemDir ( id ) , { recursive : true , force : true } ) ) ,
241+ lockFor ( input . id ) . withPermit (
242+ replaceDirectoryFiles ( itemDir ( input . id ) , input . files ) . pipe ( Effect . as ( { url : viewURL ( input . id ) } ) ) ,
243+ ) ,
244+ read : ( id ) => lockFor ( id ) . withPermit ( readDirectoryFiles ( itemDir ( id ) ) ) ,
245+ update : ( id , input ) =>
246+ lockFor ( id ) . withPermit (
247+ replaceDirectoryFiles ( itemDir ( id ) , input . files ) . pipe ( Effect . as ( { url : viewURL ( id ) } ) ) ,
248+ ) ,
249+ delete : ( id ) =>
250+ lockFor ( id ) . withPermit ( Effect . promise ( ( ) => fs . rm ( itemDir ( id ) , { recursive : true , force : true } ) ) ) ,
233251 }
234252
235253 const snapshotProviders = ( data : Data ) =>
0 commit comments