Skip to content

Commit 4d30eff

Browse files
committed
fix: anomalyco#7106 import command fails for valid share URLs
1 parent 6590c16 commit 4d30eff

3 files changed

Lines changed: 110 additions & 22 deletions

File tree

‎packages/opencode/src/cli/cmd/import.ts‎

Lines changed: 71 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,74 @@
11
import type { Argv } from "yargs"
2+
import type { Session as SDKSession, Message, Part } from "@opencode-ai/sdk/v2"
23
import { Session } from "../../session"
34
import { cmd } from "./cmd"
45
import { bootstrap } from "../bootstrap"
56
import { Storage } from "../../storage/storage"
67
import { Instance } from "../../project/instance"
8+
import { ShareNext } from "../../share/share-next"
79
import { EOL } from "os"
810

11+
/** Discriminated union returned by the ShareNext API (GET /api/share/:id/data) */
12+
export type ShareData =
13+
| { type: "session"; data: SDKSession }
14+
| { type: "message"; data: Message }
15+
| { type: "part"; data: Part }
16+
| { type: "session_diff"; data: unknown }
17+
| { type: "model"; data: unknown }
18+
19+
/** Extract share ID from a share URL like https://opncd.ai/share/abc123 */
20+
export function parseShareUrl(url: string): string | null {
21+
const match = url.match(/^https?:\/\/[^/]+\/share\/([a-zA-Z0-9_-]+)$/)
22+
return match ? match[1] : null
23+
}
24+
25+
/**
26+
* Transform ShareNext API response (flat array) into the nested structure for local file storage.
27+
*
28+
* The API returns a flat array: [session, message, message, part, part, ...]
29+
* Local storage expects: { info: session, messages: [{ info: message, parts: [part, ...] }, ...] }
30+
*
31+
* This groups parts by their messageID to reconstruct the hierarchy before writing to disk.
32+
*/
33+
export function transformShareData(shareData: ShareData[]): {
34+
info: SDKSession
35+
messages: Array<{ info: Message; parts: Part[] }>
36+
} | null {
37+
const sessionItem = shareData.find((d) => d.type === "session")
38+
if (!sessionItem) return null
39+
40+
const messageMap = new Map<string, Message>()
41+
const partMap = new Map<string, Part[]>()
42+
43+
for (const item of shareData) {
44+
if (item.type === "message") {
45+
messageMap.set(item.data.id, item.data)
46+
} else if (item.type === "part") {
47+
const messageID = item.data.messageID
48+
if (!partMap.has(messageID)) {
49+
partMap.set(messageID, [])
50+
}
51+
partMap.get(messageID)!.push(item.data)
52+
}
53+
}
54+
55+
if (messageMap.size === 0) return null
56+
57+
return {
58+
info: sessionItem.data,
59+
messages: Array.from(messageMap.values()).map((msg) => ({
60+
info: msg,
61+
parts: partMap.get(msg.id) ?? [],
62+
})),
63+
}
64+
}
65+
966
export const ImportCommand = cmd({
1067
command: "import <file>",
1168
describe: "import session data from JSON file or URL",
1269
builder: (yargs: Argv) => {
1370
return yargs.positional("file", {
14-
describe: "path to JSON file or opencode.ai share URL",
71+
describe: "path to JSON file or share URL",
1572
type: "string",
1673
demandOption: true,
1774
})
@@ -22,49 +79,42 @@ export const ImportCommand = cmd({
2279
| {
2380
info: Session.Info
2481
messages: Array<{
25-
info: any
26-
parts: any[]
82+
info: Message
83+
parts: Part[]
2784
}>
2885
}
2986
| undefined
3087

3188
const isUrl = args.file.startsWith("http://") || args.file.startsWith("https://")
3289

3390
if (isUrl) {
34-
const urlMatch = args.file.match(/https?:\/\/opncd\.ai\/share\/([a-zA-Z0-9_-]+)/)
35-
if (!urlMatch) {
36-
process.stdout.write(`Invalid URL format. Expected: https://opncd.ai/share/<slug>`)
91+
const slug = parseShareUrl(args.file)
92+
if (!slug) {
93+
const baseUrl = await ShareNext.url()
94+
process.stdout.write(`Invalid URL format. Expected: ${baseUrl}/share/<slug>`)
3795
process.stdout.write(EOL)
3896
return
3997
}
4098

41-
const slug = urlMatch[1]
42-
const response = await fetch(`https://opncd.ai/api/share/${slug}`)
99+
const baseUrl = await ShareNext.url()
100+
const response = await fetch(`${baseUrl}/api/share/${slug}/data`)
43101

44102
if (!response.ok) {
45103
process.stdout.write(`Failed to fetch share data: ${response.statusText}`)
46104
process.stdout.write(EOL)
47105
return
48106
}
49107

50-
const data = await response.json()
108+
const shareData: ShareData[] = await response.json()
109+
const transformed = transformShareData(shareData)
51110

52-
if (!data.info || !data.messages || Object.keys(data.messages).length === 0) {
53-
process.stdout.write(`Share not found: ${slug}`)
111+
if (!transformed) {
112+
process.stdout.write(`Share not found or empty: ${slug}`)
54113
process.stdout.write(EOL)
55114
return
56115
}
57116

58-
exportData = {
59-
info: data.info,
60-
messages: Object.values(data.messages).map((msg: any) => {
61-
const { parts, ...info } = msg
62-
return {
63-
info,
64-
parts,
65-
}
66-
}),
67-
}
117+
exportData = transformed
68118
} else {
69119
const file = Bun.file(args.file)
70120
exportData = await file.json().catch(() => {})

‎packages/opencode/src/share/share-next.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type * as SDK from "@opencode-ai/sdk/v2"
1111
export namespace ShareNext {
1212
const log = Log.create({ service: "share-next" })
1313

14-
async function url() {
14+
export async function url() {
1515
return Config.get().then((x) => x.enterprise?.url ?? "https://opncd.ai")
1616
}
1717

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { test, expect } from "bun:test"
2+
import { parseShareUrl, transformShareData, type ShareData } from "../../src/cli/cmd/import"
3+
4+
// parseShareUrl tests
5+
test("parses valid share URLs", () => {
6+
expect(parseShareUrl("https://opncd.ai/share/Jsj3hNIW")).toBe("Jsj3hNIW")
7+
expect(parseShareUrl("https://custom.example.com/share/abc123")).toBe("abc123")
8+
expect(parseShareUrl("http://localhost:3000/share/test_id-123")).toBe("test_id-123")
9+
})
10+
11+
test("rejects invalid URLs", () => {
12+
expect(parseShareUrl("https://opncd.ai/s/Jsj3hNIW")).toBeNull() // legacy format
13+
expect(parseShareUrl("https://opncd.ai/share/")).toBeNull()
14+
expect(parseShareUrl("https://opncd.ai/share/id/extra")).toBeNull()
15+
expect(parseShareUrl("not-a-url")).toBeNull()
16+
})
17+
18+
// transformShareData tests
19+
test("transforms share data to storage format", () => {
20+
const data: ShareData[] = [
21+
{ type: "session", data: { id: "sess-1", title: "Test" } as any },
22+
{ type: "message", data: { id: "msg-1", sessionID: "sess-1" } as any },
23+
{ type: "part", data: { id: "part-1", messageID: "msg-1" } as any },
24+
{ type: "part", data: { id: "part-2", messageID: "msg-1" } as any },
25+
]
26+
27+
const result = transformShareData(data)!
28+
29+
expect(result.info.id).toBe("sess-1")
30+
expect(result.messages).toHaveLength(1)
31+
expect(result.messages[0].parts).toHaveLength(2)
32+
})
33+
34+
test("returns null for invalid share data", () => {
35+
expect(transformShareData([])).toBeNull()
36+
expect(transformShareData([{ type: "message", data: {} as any }])).toBeNull()
37+
expect(transformShareData([{ type: "session", data: { id: "s" } as any }])).toBeNull() // no messages
38+
})

0 commit comments

Comments
 (0)