File size: 2,042 Bytes
daaf946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
export interface LoggedError {
  time: number
  request: {
    provider?: string
    model?: string
    lastMessage?: string
    [key: string]: unknown
  }
  error: string
}

const STORAGE_KEY = "tans-agents:errors"
const MAX_ERRORS = 50

function readErrors(): LoggedError[] {
  if (typeof window === "undefined") return []

  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw)
    if (!Array.isArray(parsed)) return []

    return parsed.filter((item): item is LoggedError => {
      return (
        item &&
        typeof item.time === "number" &&
        typeof item.request === "object" &&
        typeof item.error === "string"
      )
    })
  } catch {
    return []
  }
}

function writeErrors(errors: LoggedError[]) {
  if (typeof window === "undefined") return
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(errors.slice(0, MAX_ERRORS)))
}

export function logError(err: LoggedError) {
  const next = [err, ...readErrors()].slice(0, MAX_ERRORS)
  writeErrors(next)
}

export function getErrors() {
  return readErrors()
}

export function clearErrors() {
  if (typeof window === "undefined") return
  window.localStorage.removeItem(STORAGE_KEY)
}

export function formatBugReport(errors: LoggedError[]) {
  if (errors.length === 0) return "## AI Error Log\n\nNo errors recorded."

  return [
    "## AI Error Log",
    "",
    ...errors.flatMap((entry, index) => [
      `### ${index + 1}. ${new Date(entry.time).toISOString()}`,
      "",
      `- Provider: ${entry.request.provider ?? "unknown"}`,
      `- Model: ${entry.request.model ?? "unknown"}`,
      `- Error: ${entry.error}`,
      "",
      "```json",
      JSON.stringify(entry.request, null, 2),
      "```",
      "",
    ]),
  ].join("\n")
}

export async function copyAsBugReport(errors: LoggedError[]) {
  const report = formatBugReport(errors)
  if (typeof navigator !== "undefined" && navigator.clipboard) {
    await navigator.clipboard.writeText(report)
  }
  return report
}