This commit captures both the prior accumulated work-in-progress
(framework migration web/→svelte/, postgres storage, conversation
viewer, dashboard auth, OpenAPI spec, integration tests) AND today's
operational improvements layered on top. History wasn't checkpointed
incrementally; happy to split it via interactive rebase if a reviewer
wants smaller commits.
Today's changes (in addition to the older WIP):
1. Configurable upstream response-header timeout
- ANTHROPIC_RESPONSE_HEADER_TIMEOUT env (default 300s)
- Replaces hardcoded 300s in provider/anthropic.go that was firing
on opus + 1M-context + extended thinking non-streaming requests
- Files: internal/config/config.go, internal/provider/anthropic.go
2. Structured forward-error diagnostic logging
- When a forward to Anthropic fails, log a single key=value line
with request_id, model, stream, body_bytes, has_thinking,
anthropic_beta, query, elapsed, ctx_err — alongside the existing
human-readable error line for back-compat
- Files: internal/handler/handlers.go (logForwardFailure)
3. Full SSE protocol passthrough + Flusher fix
- handler/handlers.go: forward all SSE lines verbatim (event:, id:,
retry:, : comments, blank-line terminators), not only data:.
Previous code produced malformed SSE for strict parsers.
- middleware/logging.go: explicit Flush() method on responseWriter.
Embedding http.ResponseWriter (interface) does not auto-promote
Flush(), so every w.(http.Flusher) check in the streaming
handler was returning ok=false and SSE writes buffered in net/http
until the body closed.
4. Non-streaming → streaming demotion (feature-flagged)
- ANTHROPIC_DEMOTE_NONSTREAMING env (default false)
- When enabled and the routed provider is anthropic, force stream=true
upstream for clients that asked for stream=false. Receive SSE,
accumulate via accumulateSSEToMessage (handles text, tool_use with
partial_json reassembly, thinking, signature, citations_delta,
usage merge), and synthesize a single non-streaming JSON response.
- Eliminates the ResponseHeaderTimeout class of failure entirely.
- Body rewrite uses json.Decoder + UseNumber() to preserve integer
precision in unknown nested fields (tool inputs from prior turns).
- Files: internal/config/config.go, internal/handler/handlers.go,
cmd/proxy/main.go, cmd/proxy/main_test.go
5. Live operational state: /livez gauge + graceful drain
- New internal/runtime package: atomic in-flight counter + draining flag
- New middleware/inflight.go: increments runtime gauge, applied to
/v1/* subrouter so Messages, ChatCompletions, and ProxyPassthrough
are all counted
- /v1/* moved to a gorilla/mux subrouter so the InFlight middleware
applies surgically; /health, /livez, /openapi.* remain on parent
router (unauthenticated, uncounted)
- Health handler returns 503 draining when runtime.IsDraining() is
true, so Traefik stops routing to a slot before drain begins
- New /livez handler returns {status, in_flight, draining, timestamp}
- SIGTERM handler in main.go: SetDraining(true), poll for in_flight==0
with 32-min ceiling and 1s tick (logs every 10s), then srv.Shutdown
- Auth bypass list extended with /livez
- Files: internal/runtime/runtime.go (new),
internal/middleware/inflight.go (new),
internal/middleware/auth.go,
internal/handler/handlers.go (Health, Livez, runtime import),
cmd/proxy/main.go (subrouter, drain loop)
6. OpenAPI spec updates
- Document Health 503 response and new DrainingResponse schema
- Add /livez path with LivezResponse schema
- Files: internal/handler/openapi.go
Verified: go build ./... clean, go test ./... all pass, go vet clean.
Three rounds of codex peer review across changes 1-5; all feedback
addressed (citations_delta, json.Number precision, drain-loop logging
via lastLog timestamp, PathPrefix tightened to "/v1/").
104 lines
3.8 KiB
Svelte
104 lines
3.8 KiB
Svelte
<script lang="ts">
|
|
import {
|
|
User, Bot, Settings, Eye, EyeOff, Code
|
|
} from 'lucide-svelte';
|
|
import RichText from '$lib/components/RichText.svelte';
|
|
import ChatToolBlock from '$lib/components/ChatToolBlock.svelte';
|
|
import ChatOutsideBlock from '$lib/components/ChatOutsideBlock.svelte';
|
|
import { formatJSON } from '$lib/formatters';
|
|
import {
|
|
splitContent,
|
|
isToolResultBlock,
|
|
isToolUseBlock,
|
|
type OutsideItem
|
|
} from '$lib/chat-utils';
|
|
import type { RequestMessage, ToolResultContentBlock } from '$lib/types';
|
|
|
|
interface Props {
|
|
/** The message to render. */
|
|
message: RequestMessage;
|
|
/** Index of this message in the messages array. */
|
|
idx: number;
|
|
/** The full messages array (needed to check next message for "Delivered"). */
|
|
messages: RequestMessage[];
|
|
/** Map of tool_use_id -> tool_result for pairing. */
|
|
toolResultMap: Map<string, ToolResultContentBlock>;
|
|
/** Expanded raw sections state. */
|
|
expandedRawSections: Record<string, boolean>;
|
|
/** Toggle a raw section. */
|
|
onToggleRaw: (key: string) => void;
|
|
}
|
|
|
|
let { message, idx, messages, toolResultMap, expandedRawSections, onToggleRaw }: Props = $props();
|
|
|
|
let isUser = $derived(message.role === 'user');
|
|
let isAssistant = $derived(message.role === 'assistant');
|
|
let split = $derived(splitContent(message.content));
|
|
</script>
|
|
|
|
<!-- Outside-bubble blocks: everything that isn't plain text -->
|
|
{#each split.outside as item, oi}
|
|
{#if isToolResultBlock(item) && item.tool_use_id && toolResultMap.has(item.tool_use_id)}
|
|
<!-- Paired tool result -- already rendered with its tool_use -->
|
|
{:else if isToolUseBlock(item) && item.id && toolResultMap.has(item.id)}
|
|
<ChatToolBlock
|
|
{item}
|
|
result={toolResultMap.get(item.id)}
|
|
rawKey={`out-${idx}-${oi}`}
|
|
{expandedRawSections}
|
|
{onToggleRaw}
|
|
/>
|
|
{:else}
|
|
<ChatOutsideBlock
|
|
{item}
|
|
rawKey={`out-${idx}-${oi}`}
|
|
{expandedRawSections}
|
|
{onToggleRaw}
|
|
/>
|
|
{/if}
|
|
{/each}
|
|
|
|
<!-- Chat bubble -- only plain text content -->
|
|
{#if split.chat}
|
|
<div class="flex {isUser ? 'justify-end' : 'justify-start'}">
|
|
<div class="max-w-[85%]">
|
|
<div class="flex items-start space-x-2 {isUser ? 'flex-row-reverse space-x-reverse' : ''}">
|
|
<div class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center {isUser ? 'bg-blue-100' : isAssistant ? 'bg-gray-100' : 'bg-amber-100'}">
|
|
{#if isUser}
|
|
<User class="w-4 h-4 text-blue-600" />
|
|
{:else if isAssistant}
|
|
<Bot class="w-4 h-4 text-gray-600" />
|
|
{:else}
|
|
<Settings class="w-4 h-4 text-amber-600" />
|
|
{/if}
|
|
</div>
|
|
<div class="min-w-0">
|
|
<div class="{isUser ? 'bg-blue-500 text-white' : isAssistant ? 'bg-gray-200 text-gray-900' : 'bg-amber-50 border border-amber-200 text-gray-900'} rounded-2xl {isUser ? 'rounded-tr-sm' : 'rounded-tl-sm'} px-4 py-3 shadow-sm">
|
|
<RichText text={split.chat} variant={isUser ? 'inverse' : 'default'} />
|
|
</div>
|
|
{#if isUser && idx < messages.length - 1 && messages[idx + 1]?.role === 'assistant'}
|
|
<div class="flex justify-end mt-0.5 px-1">
|
|
<span class="text-[10px] text-gray-400">Delivered</span>
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- Raw view -- rendered outside the bubble layout so it doesn't resize it -->
|
|
<div class="px-10 {isUser ? 'text-right' : ''}">
|
|
<button
|
|
onclick={() => onToggleRaw(`msg-${idx}`)}
|
|
class="text-[10px] text-gray-400 hover:text-gray-600 inline-flex items-center space-x-1 transition-colors mt-0.5"
|
|
>
|
|
{#if expandedRawSections[`msg-${idx}`]}
|
|
<EyeOff class="w-3 h-3" /><span>Hide raw</span>
|
|
{:else}
|
|
<Eye class="w-3 h-3" /><span>View raw</span>
|
|
{/if}
|
|
</button>
|
|
{#if expandedRawSections[`msg-${idx}`]}
|
|
<pre class="mt-1 text-[10px] bg-gray-900 text-gray-300 rounded-lg p-3 overflow-x-auto max-h-48 font-mono text-left">{formatJSON(message, 0)}</pre>
|
|
{/if}
|
|
</div>
|
|
{/if}
|