Frank 9 месяцев назад
Родитель
Сommit
c203891b84

+ 31 - 40
app/packages/function/src/api.ts

@@ -7,16 +7,6 @@ type Bindings = {
 }
 
 export class SyncServer extends DurableObject {
-  private files: Map<string, string> = new Map()
-  private shareID?: string
-
-  constructor(ctx: DurableObjectState, env: Bindings) {
-    super(ctx, env)
-    this.ctx.blockConcurrencyWhile(async () => {
-      this.files = await this.ctx.storage.list()
-    })
-  }
-
   async fetch(req: Request) {
     console.log("SyncServer subscribe")
 
@@ -25,10 +15,12 @@ export class SyncServer extends DurableObject {
 
     this.ctx.acceptWebSocket(server)
 
-    setTimeout(() => {
-      this.files.forEach((content, key) =>
-        server.send(JSON.stringify({ key, content })),
-      )
+    setTimeout(async () => {
+      const data = await this.ctx.storage.list()
+      data.forEach((content, key) => {
+        if (key === "shareID") return
+        server.send(JSON.stringify({ key, content }))
+      })
     }, 0)
 
     return new Response(null, {
@@ -44,7 +36,6 @@ export class SyncServer extends DurableObject {
   }
 
   async publish(key: string, content: string) {
-    this.files.set(key, content)
     await this.ctx.storage.put(key, content)
 
     const clients = this.ctx.getWebSockets()
@@ -53,16 +44,15 @@ export class SyncServer extends DurableObject {
   }
 
   async setShareID(shareID: string) {
-    this.shareID = shareID
+    await this.ctx.storage.put("shareID", shareID)
   }
 
   async getShareID() {
-    return this.shareID
+    return this.ctx.storage.get("shareID")
   }
 
   async clear() {
     await this.ctx.storage.deleteAll()
-    this.files.clear()
   }
 }
 
@@ -82,14 +72,11 @@ export default {
       // Get existing shareID
       const id = env.SYNC_SERVER.idFromName(sessionID)
       const stub = env.SYNC_SERVER.get(id)
-      let shareID = await stub.getShareID()
-      if (!shareID) {
-        shareID = randomUUID()
-        await stub.setShareID(shareID)
-      }
+      if (await stub.getShareID())
+        return new Response("Error: Session already shared", { status: 400 })
 
-      // Store session ID
-      await Resource.Bucket.put(`${shareID}/session/id`, sessionID)
+      const shareID = randomUUID()
+      await stub.setShareID(shareID)
 
       return new Response(JSON.stringify({ shareID }), {
         headers: { "Content-Type": "application/json" },
@@ -100,12 +87,16 @@ export default {
       const sessionID = body.sessionID
       const shareID = body.shareID
 
-      // Delete from bucket
-      await Resource.Bucket.delete(`${shareID}/session/id`)
+      // validate shareID
+      if (!shareID)
+        return new Response("Error: Share ID is required", { status: 400 })
 
       // Delete from durable object
       const id = env.SYNC_SERVER.idFromName(sessionID)
       const stub = env.SYNC_SERVER.get(id)
+      if ((await stub.getShareID()) !== shareID)
+        return new Response("Error: Share ID does not match", { status: 400 })
+
       await stub.clear()
 
       return new Response(JSON.stringify({}), {
@@ -119,6 +110,8 @@ export default {
       const key = body.key
       const content = body.content
 
+      console.log("share_sync", sessionID, shareID, key, content)
+
       // validate key
       if (
         !key.startsWith(`session/info/${sessionID}`) &&
@@ -126,13 +119,16 @@ export default {
       )
         return new Response("Error: Invalid key", { status: 400 })
 
-      const ret = await Resource.Bucket.get(`${shareID}/session/id`)
-      if (!ret)
-        return new Response("Error: Session not shared", { status: 400 })
+      // validate shareID
+      if (!shareID)
+        return new Response("Error: Share ID is required", { status: 400 })
 
       // send message to server
       const id = env.SYNC_SERVER.idFromName(sessionID)
       const stub = env.SYNC_SERVER.get(id)
+      if ((await stub.getShareID()) !== shareID)
+        return new Response("Error: Share ID does not match", { status: 400 })
+
       await stub.publish(key, content)
 
       // store message
@@ -153,21 +149,16 @@ export default {
       }
 
       // get query parameters
-      const shareID = url.searchParams.get("shareID")
-      if (!shareID)
-        return new Response("Error: Share ID is required", { status: 400 })
-
-      // Get session ID
-      const sessionID = await Resource.Bucket.get(`${shareID}/session/id`).then(
-        (res) => res?.text(),
-      )
-      console.log("sessionID", sessionID)
+      const sessionID = url.searchParams.get("id")
       if (!sessionID)
-        return new Response("Error: Session not shared", { status: 400 })
+        return new Response("Error: Share ID is required", { status: 400 })
 
       // subscribe to server
       const id = env.SYNC_SERVER.idFromName(sessionID)
       const stub = env.SYNC_SERVER.get(id)
+      if (!(await stub.getShareID()))
+        return new Response("Error: Session not shared", { status: 400 })
+
       return stub.fetch(request)
     }
   },

+ 9 - 9
app/packages/web/src/components/Share.tsx

@@ -16,7 +16,7 @@ type SessionInfo = {
 
 export default function Share(props: { api: string }) {
   let params = new URLSearchParams(document.location.search)
-  const shareId = params.get("id")
+  const sessionId = params.get("id")
 
   const [connectionStatus, setConnectionStatus] = createSignal("Disconnected")
   const [sessionInfo, setSessionInfo] = createSignal<SessionInfo | null>(null)
@@ -27,12 +27,12 @@ export default function Share(props: { api: string }) {
   onMount(() => {
     const apiUrl = props.api
 
-    console.log("Mounting Share component with ID:", shareId)
+    console.log("Mounting Share component with ID:", sessionId)
     console.log("API URL:", apiUrl)
 
-    if (!shareId) {
-      console.error("Share ID not found in environment variables")
-      setConnectionStatus("Error: Share ID not found")
+    if (!sessionId) {
+      console.error("Session ID not found in environment variables")
+      setConnectionStatus("Error: Session ID not found")
       return
     }
 
@@ -56,7 +56,7 @@ export default function Share(props: { api: string }) {
 
       // Always use secure WebSocket protocol (wss)
       const wsBaseUrl = apiUrl.replace(/^https?:\/\//, "wss://")
-      const wsUrl = `${wsBaseUrl}/share_poll?shareID=${shareId}`
+      const wsUrl = `${wsBaseUrl}/share_poll?id=${sessionId}`
       console.log("Connecting to WebSocket URL:", wsUrl)
 
       // Create WebSocket connection
@@ -144,7 +144,7 @@ export default function Share(props: { api: string }) {
 
   return (
     <main>
-      <h1>Share: {shareId}</h1>
+      <h1>Share: {sessionId}</h1>
 
       <div style={{ margin: "2rem 0" }}>
         <h2>WebSocket Connection</h2>
@@ -300,8 +300,8 @@ export default function Share(props: { api: string }) {
                         const parsed = JSON.parse(msg.content) as UIMessage
                         const createdTime = parsed.metadata?.time?.created
                           ? new Date(
-                            parsed.metadata.time.created,
-                          ).toLocaleString()
+                              parsed.metadata.time.created,
+                            ).toLocaleString()
                           : "Unknown time"
 
                         return (

+ 9 - 0
app/packages/web/sst-env.d.ts

@@ -0,0 +1,9 @@
+/* This file is auto-generated by SST. Do not edit. */
+/* tslint:disable */
+/* eslint-disable */
+/* deno-fmt-ignore-file */
+
+/// <reference path="../../sst-env.d.ts" />
+
+import "sst"
+export {}

+ 4 - 4
js/src/index.ts

@@ -24,11 +24,11 @@ cli.command("generate", "Generate OpenAPI and event specs").action(async () => {
   await fs.mkdir(dir, { recursive: true });
   await Bun.write(
     path.join(dir, "openapi.json"),
-    JSON.stringify(specs, null, 2),
+    JSON.stringify(specs, null, 2)
   );
   await Bun.write(
     path.join(dir, "event.json"),
-    JSON.stringify(Bus.specs(), null, 2),
+    JSON.stringify(Bus.specs(), null, 2)
   );
 });
 
@@ -41,7 +41,7 @@ cli
       const session = await Session.create();
       const shareID = await Session.share(session.id);
       if (shareID)
-        console.log("Share ID: https://dev.opencode.ai/share/" + shareID);
+        console.log("Share ID: https://dev.opencode.ai/share?id=" + session.id);
       const result = await Session.chat(session.id, {
         type: "text",
         text: message.join(" "),
@@ -58,7 +58,7 @@ cli
             part.toolInvocation.args,
             part.toolInvocation.state === "result"
               ? part.toolInvocation.result
-              : "",
+              : ""
           );
         }
       }