Function bodies 85 total
main.main function · go · L18-L96 (79 LOC)cmd/opencode-chat/main.go
func main() {
port := flag.Int("port", 8080, "Port to serve HTTP")
flag.Parse()
log.Printf("Starting OpenCode Chat on port %d", *port)
srv, err := server.NewServer()
if err != nil {
log.Fatalf("Failed to create server: %v", err)
}
log.Printf("Templates loaded successfully")
log.Printf("Initializing sandbox...")
authConfig, err := sandbox.LoadAuthConfig()
if err != nil {
log.Fatalf("Failed to load auth config: %v", err)
}
srv.Sandbox = sandbox.NewLocalDockerSandbox()
if err := srv.Sandbox.Start(authConfig); err != nil {
log.Fatalf("Failed to start sandbox: %v", err)
}
defer func() {
log.Println("Defer: Cleaning up sandbox")
if err := srv.Sandbox.Stop(); err != nil {
log.Printf("Error stopping sandbox: %v", err)
}
}()
log.Printf("Sandbox ready at %s", srv.Sandbox.OpencodeURL())
log.Printf("Initializing workspace session...")
if err := srv.InitWorkspaceSession(); err != nil {
log.Fatalf("Failed to initialize workspace session: %v", err)
}
loauth.GetAuthContext function · go · L26-L31 (6 LOC)internal/auth/auth.go
func GetAuthContext(r *http.Request) AuthContext {
if ctx, ok := r.Context().Value(authContextKey{}).(AuthContext); ok {
return ctx
}
return AuthContext{}
}auth.GenerateSessionID function · go · L39-L45 (7 LOC)internal/auth/auth.go
func GenerateSessionID() string {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
panic(err)
}
return hex.EncodeToString(bytes)
}middleware.ChainMiddleware function · go · L17-L22 (6 LOC)internal/middleware/middleware.go
func ChainMiddleware(handler http.Handler, middlewares ...Middleware) http.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
handler = middlewares[i](handler)
}
return handler
}middleware.NewLoggingResponseWriter function · go · L32-L38 (7 LOC)internal/middleware/middleware.go
func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
return &LoggingResponseWriter{
ResponseWriter: w,
StatusCode: 200,
Body: &bytes.Buffer{},
}
}middleware.LoggingResponseWriter.Hijack method · go · L51-L56 (6 LOC)internal/middleware/middleware.go
func (lw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := lw.ResponseWriter.(http.Hijacker); ok {
return hj.Hijack()
}
return nil, nil, fmt.Errorf("underlying ResponseWriter does not implement http.Hijacker")
}middleware.LoggingMiddleware function · go · L71-L85 (15 LOC)internal/middleware/middleware.go
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Special handling for SSE endpoint - don't buffer the entire stream
if r.URL.Path == "/events" {
log.Printf("WIRE_OUT SSE connection started: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
log.Printf("WIRE_OUT SSE connection ended: %s %s", r.Method, r.URL.Path)
return
}
lw := NewLoggingResponseWriter(w)
next.ServeHTTP(lw, r)
lw.LogResponse(r.Method, r.URL.Path)
})
}Source: Repobility analyzer · https://repobility.com
sandbox.LocalDockerSandbox.Start method · go · L38-L78 (41 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) Start(apiKeys map[string]models.AuthConfig) error {
ld.ctx, ld.cancel = context.WithCancel(context.Background())
if err := ld.cleanupOrphanedContainers(); err != nil {
log.Printf("LocalDocker: Warning - failed to cleanup orphaned containers: %v", err)
}
var err error
ld.port, err = FindFreePort()
if err != nil {
return fmt.Errorf("failed to find free port for OpenCode: %w", err)
}
log.Printf("LocalDocker: Allocated port %d for OpenCode", ld.port)
ld.gottyPort, err = FindFreePort()
if err != nil {
return fmt.Errorf("failed to find free port for Gotty: %w", err)
}
log.Printf("LocalDocker: Allocated port %d for Gotty", ld.gottyPort)
ld.authFile, err = CreateAuthFile(apiKeys)
if err != nil {
return fmt.Errorf("failed to create auth file: %w", err)
}
log.Printf("LocalDocker: Created auth file at %s", ld.authFile)
if err := ld.ensureImage(); err != nil {
return fmt.Errorf("failed to ensure Docker image: %w", err)
}
if err := ldsandbox.LocalDockerSandbox.OpencodeURL method · go · L80-L90 (11 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) OpencodeURL() string {
return fmt.Sprintf("http://localhost:%d", ld.port)
}
func (ld *LocalDockerSandbox) GottyURL() string {
log.Printf("LocalDocker.GottyURL: gottyPort=%d", ld.gottyPort)
if ld.gottyPort == 0 {
return ""
}
return fmt.Sprintf("http://localhost:%d", ld.gottyPort)
}sandbox.LocalDockerSandbox.GottyURL method · go · L84-L110 (27 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) GottyURL() string {
log.Printf("LocalDocker.GottyURL: gottyPort=%d", ld.gottyPort)
if ld.gottyPort == 0 {
return ""
}
return fmt.Sprintf("http://localhost:%d", ld.gottyPort)
}
func (ld *LocalDockerSandbox) DownloadZip() (io.ReadCloser, error) {
if !ld.IsRunning() {
return nil, fmt.Errorf("sandbox is not running")
}
cmd := exec.CommandContext(ld.ctx, "docker", "exec", ld.containerName,
"sh", "-c", "cd /app && ([ -z \"$(ls -A .)\" ] && echo 'Empty workspace' > .placeholder || true) && zip -r - . 2>/dev/null")
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start zip command: %w", err)
}
return &processReader{stdout: stdout, cmd: cmd}, nil
}sandbox.LocalDockerSandbox.DownloadZip method · go · L92-L110 (19 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) DownloadZip() (io.ReadCloser, error) {
if !ld.IsRunning() {
return nil, fmt.Errorf("sandbox is not running")
}
cmd := exec.CommandContext(ld.ctx, "docker", "exec", ld.containerName,
"sh", "-c", "cd /app && ([ -z \"$(ls -A .)\" ] && echo 'Empty workspace' > .placeholder || true) && zip -r - . 2>/dev/null")
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start zip command: %w", err)
}
return &processReader{stdout: stdout, cmd: cmd}, nil
}sandbox.processReader.Close method · go · L121-L129 (9 LOC)internal/sandbox/docker.go
func (pr *processReader) Close() error {
if err := pr.stdout.Close(); err != nil {
log.Printf("Error closing stdout: %v", err)
}
if err := pr.cmd.Wait(); err != nil {
log.Printf("Process exit error: %v", err)
}
return nil
}sandbox.LocalDockerSandbox.Stop method · go · L131-L184 (54 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) Stop() error {
if ld.cancel != nil {
ld.cancel()
ld.cancel = nil
}
var errors []string
if ld.containerName != "" {
log.Printf("LocalDocker: Stopping container %s", ld.containerName)
if ld.containerExists() {
stopCmd := exec.Command("docker", "stop", "--time=5", ld.containerName)
if err := stopCmd.Run(); err != nil {
log.Printf("LocalDocker: Graceful stop failed for %s: %v", ld.containerName, err)
}
rmCmd := exec.Command("docker", "rm", "-f", ld.containerName)
if err := rmCmd.Run(); err != nil {
rmRetryCmd := exec.Command("docker", "container", "rm", "-f", ld.containerName)
if retryErr := rmRetryCmd.Run(); retryErr != nil {
errors = append(errors, fmt.Sprintf("failed to remove container %s: %v (retry: %v)", ld.containerName, err, retryErr))
} else {
log.Printf("LocalDocker: Force removed container %s (retry succeeded)", ld.containerName)
}
} else {
log.Printf("LocalDocker: Force removed consandbox.LocalDockerSandbox.containerExists method · go · L186-L192 (7 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) containerExists() bool {
if ld.containerName == "" {
return false
}
cmd := exec.Command("docker", "inspect", ld.containerName)
return cmd.Run() == nil
}sandbox.LocalDockerSandbox.IsRunning method · go · L194-L204 (11 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) IsRunning() bool {
if ld.containerName == "" {
return false
}
cmd := exec.Command("docker", "ps", "-q", "-f", fmt.Sprintf("name=%s", ld.containerName))
output, err := cmd.Output()
if err != nil {
return false
}
return strings.TrimSpace(string(output)) != ""
}Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
sandbox.LocalDockerSandbox.ContainerIP method · go · L206-L223 (18 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) ContainerIP() string {
if ld.containerName == "" || !ld.IsRunning() {
return ""
}
// Try the network-specific path first (works on all Docker versions),
// then fall back to the top-level field for older Docker versions.
cmd := exec.Command("docker", "inspect", "--format", `{{(index .NetworkSettings.Networks "bridge").IPAddress}}`, ld.containerName)
output, err := cmd.Output()
if err != nil || strings.TrimSpace(string(output)) == "" {
cmd = exec.Command("docker", "inspect", "--format", "{{.NetworkSettings.IPAddress}}", ld.containerName)
output, err = cmd.Output()
if err != nil {
log.Printf("Failed to get container IP: %v", err)
return ""
}
}
return strings.TrimSpace(string(output))
}sandbox.LocalDockerSandbox.ensureImage method · go · L225-L237 (13 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) ensureImage() error {
cmd := exec.Command("docker", "images", "-q", dockerImageName+":latest")
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to check image: %w", err)
}
if strings.TrimSpace(string(output)) != "" {
log.Printf("LocalDocker: Image %s already exists", dockerImageName)
return nil
}
log.Printf("LocalDocker: Building image %s", dockerImageName)
return ld.buildImage()
}sandbox.LocalDockerSandbox.buildImage method · go · L239-L256 (18 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) buildImage() error {
root, err := findProjectRoot()
if err != nil {
return fmt.Errorf("failed to find project root: %w", err)
}
cmd := exec.CommandContext(ld.ctx, "docker", "build",
"-t", dockerImageName+":latest",
"-f", "sandbox/Dockerfile",
".")
cmd.Dir = root
output, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Docker build output: %s", string(output))
return fmt.Errorf("failed to build Docker image: %w", err)
}
log.Printf("LocalDocker: Build completed successfully")
return nil
}sandbox.findProjectRoot function · go · L260-L275 (16 LOC)internal/sandbox/docker.go
func findProjectRoot() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
for {
if _, err := os.Stat(dir + "/go.mod"); err == nil {
return dir, nil
}
parent := dir[:strings.LastIndex(dir, "/")]
if parent == dir {
return "", fmt.Errorf("go.mod not found in any parent directory")
}
dir = parent
}
}sandbox.LocalDockerSandbox.createContainer method · go · L277-L296 (20 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) createContainer() error {
ld.containerName = fmt.Sprintf("%s%d", containerPrefix, time.Now().Unix())
cmd := exec.CommandContext(ld.ctx, "docker", "run", "-d",
"--init",
"--name", ld.containerName,
"-p", fmt.Sprintf("127.0.0.1:%d:8080", ld.port),
"-p", fmt.Sprintf("127.0.0.1:%d:8081", ld.gottyPort),
"-v", fmt.Sprintf("%s:/home/opencode/.local/share/opencode/auth.json:ro", ld.authFile),
dockerImageName+":latest")
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to start container: %w", err)
}
ld.containerID = strings.TrimSpace(string(output))
log.Printf("LocalDocker: Started container %s (%s) on port %d", ld.containerName, ld.containerID[:12], ld.port)
return nil
}sandbox.LocalDockerSandbox.cleanupOrphanedContainers method · go · L302-L331 (30 LOC)internal/sandbox/docker.go
func (ld *LocalDockerSandbox) cleanupOrphanedContainers() error {
cmd := exec.Command("docker", "ps", "-a", "-q", "--filter", "name="+containerPrefix)
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to list orphaned containers: %w", err)
}
containerIDs := strings.Fields(strings.TrimSpace(string(output)))
if len(containerIDs) == 0 {
log.Printf("LocalDocker: No orphaned containers to clean up")
return nil
}
log.Printf("LocalDocker: Found %d orphaned containers, cleaning up...", len(containerIDs))
for _, containerID := range containerIDs {
nameCmd := exec.Command("docker", "inspect", "--format", "{{.Name}}", containerID)
nameOutput, _ := nameCmd.Output()
containerName := strings.TrimSpace(strings.TrimPrefix(string(nameOutput), "/"))
stopCmd := exec.Command("docker", "rm", "-f", containerID)
if err := stopCmd.Run(); err != nil {
log.Printf("LocalDocker: Warning - failed to remove orphaned container %s (%s): %v", containerName, containersandbox.NewFlyIOSandbox function · go · L20-L25 (6 LOC)internal/sandbox/flyio.go
func NewFlyIOSandbox(authToken, region string) *FlyIOSandbox {
return &FlyIOSandbox{
authToken: authToken,
region: region,
}
}sandbox.FlyIOSandbox.OpencodeURL method · go · L31-L36 (6 LOC)internal/sandbox/flyio.go
func (fs *FlyIOSandbox) OpencodeURL() string {
if fs.url == "" {
return ""
}
return fs.url
}Want fix-PRs on findings? Install Repobility's GitHub App · github.com/apps/repobility-bot
sandbox.LoadAuthConfig function · go · L43-L64 (22 LOC)internal/sandbox/sandbox.go
func LoadAuthConfig() (map[string]models.AuthConfig, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
authPath := filepath.Join(homeDir, ".local", "share", "opencode", "auth.json")
log.Printf("TESTING: Loading auth config from %s", authPath)
authData, err := os.ReadFile(authPath)
if err != nil {
return nil, fmt.Errorf("failed to read auth config: %w", err)
}
var authConfig map[string]models.AuthConfig
if err := json.Unmarshal(authData, &authConfig); err != nil {
return nil, fmt.Errorf("failed to parse auth config: %w", err)
}
log.Printf("TESTING: Loaded auth config for %d providers", len(authConfig))
return authConfig, nil
}sandbox.FindFreePort function · go · L67-L80 (14 LOC)internal/sandbox/sandbox.go
func FindFreePort() (int, error) {
listener, err := net.Listen("tcp", ":0")
if err != nil {
return 0, err
}
defer listener.Close()
addr, ok := listener.Addr().(*net.TCPAddr)
if !ok {
return 0, fmt.Errorf("failed to get TCP address")
}
return addr.Port, nil
}sandbox.CreateAuthFile function · go · L83-L100 (18 LOC)internal/sandbox/sandbox.go
func CreateAuthFile(authConfig map[string]models.AuthConfig) (string, error) {
tmpFile, err := os.CreateTemp("", "opencode-auth-*.json")
if err != nil {
return "", fmt.Errorf("failed to create temp auth file: %w", err)
}
defer tmpFile.Close()
authData, err := json.MarshalIndent(authConfig, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal auth config: %w", err)
}
if _, err := tmpFile.Write(authData); err != nil {
return "", fmt.Errorf("failed to write auth file: %w", err)
}
return tmpFile.Name(), nil
}sandbox.StaticURLSandbox.DownloadZip method · go · L28-L33 (6 LOC)internal/sandbox/teststub.go
func (s *StaticURLSandbox) DownloadZip() (io.ReadCloser, error) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
_ = zw.Close()
return io.NopCloser(bytes.NewReader(buf.Bytes())), nil
}server.Server.isAuthenticated method · go · L12-L23 (12 LOC)internal/server/handlers_auth.go
func (s *Server) isAuthenticated(r *http.Request) bool {
cookie, err := r.Cookie("auth_session")
if err != nil {
return false
}
s.mu.RLock()
defer s.mu.RUnlock()
_, exists := s.authSessions[cookie.Value]
return exists
}server.Server.getAuthSession method · go · L26-L37 (12 LOC)internal/server/handlers_auth.go
func (s *Server) getAuthSession(r *http.Request) (*auth.AuthSession, bool) {
cookie, err := r.Cookie("auth_session")
if err != nil {
return nil, false
}
s.mu.RLock()
defer s.mu.RUnlock()
session, exists := s.authSessions[cookie.Value]
return session, exists
}server.Server.withAuth method · go · L40-L47 (8 LOC)internal/server/handlers_auth.go
func (s *Server) withAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, ok := s.getAuthSession(r)
authCtx := auth.AuthContext{Session: session, IsAuthenticated: ok}
ctx := auth.SetAuthContext(r.Context(), authCtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}server.Server.requireAuth method · go · L50-L64 (15 LOC)internal/server/handlers_auth.go
func (s *Server) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if authCtx := auth.GetAuthContext(r); authCtx.IsAuthenticated {
next.ServeHTTP(w, r)
return
}
if s.isAuthenticated(r) {
next.ServeHTTP(w, r)
return
}
http.Redirect(w, r, "/login", http.StatusSeeOther)
})
}Repobility (the analyzer behind this table) · https://repobility.com
server.Server.createAuthSession method · go · L67-L87 (21 LOC)internal/server/handlers_auth.go
func (s *Server) createAuthSession(w http.ResponseWriter, email string) string {
sessionID := auth.GenerateSessionID()
s.mu.Lock()
s.authSessions[sessionID] = &auth.AuthSession{
Email: email,
CreatedAt: time.Now(),
}
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "auth_session",
Value: sessionID,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: 86400 * 7,
})
return sessionID
}server.Server.clearAuthSession method · go · L90-L105 (16 LOC)internal/server/handlers_auth.go
func (s *Server) clearAuthSession(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("auth_session")
if err == nil {
s.mu.Lock()
delete(s.authSessions, cookie.Value)
s.mu.Unlock()
}
http.SetCookie(w, &http.Cookie{
Name: "auth_session",
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
}server.Server.handleLoginGET method · go · L107-L123 (17 LOC)internal/server/handlers_auth.go
func (s *Server) handleLoginGET(w http.ResponseWriter, r *http.Request) {
authCtx := auth.GetAuthContext(r)
if authCtx.IsAuthenticated {
http.Redirect(w, r, "/projects", http.StatusSeeOther)
return
}
hasContent := r.URL.Query().Get("hasContent") == "true"
data := struct {
HasContent bool
}{
HasContent: hasContent,
}
s.renderHTML(w, "login", data)
}server.Server.handleLoginPOST method · go · L125-L140 (16 LOC)internal/server/handlers_auth.go
func (s *Server) handleLoginPOST(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form data", http.StatusBadRequest)
return
}
email := r.FormValue("email")
s.createAuthSession(w, email)
hasContent := r.URL.Query().Get("hasContent") == "true"
if hasContent {
http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/projects", http.StatusSeeOther)
}
}server.Server.handleProjects method · go · L147-L221 (75 LOC)internal/server/handlers_auth.go
func (s *Server) handleProjects(w http.ResponseWriter, r *http.Request) {
authCtx := auth.GetAuthContext(r)
authSession := authCtx.Session
userInitial := "U"
if authSession != nil && len(authSession.Email) > 0 {
userInitial = strings.ToUpper(string(authSession.Email[0]))
}
type Project struct {
ID string
Name string
Type string
Language string
FileCount int
LineCount int
CreatedAt string
UpdatedAt string
}
projects := []Project{
{
ID: "proj1",
Name: "E-Commerce Platform",
Type: "Web",
Language: "TypeScript",
FileCount: 156,
LineCount: 12453,
CreatedAt: "Jan 5, 2025",
UpdatedAt: "2 hours ago",
},
{
ID: "proj2",
Name: "User Auth Service",
Type: "API",
Language: "Go",
FileCount: 42,
LineCount: 3567,
CreatedAt: "Dec 28, 2024",
UpdatedAt: "Yesterday",
},
{
ID: "proj3",
Name: "MCP Tool",
Type: "MCP",
Language: "Python",
server.Server.handleIndex method · go · L20-L62 (43 LOC)internal/server/handlers_chat.go
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
cookie, _ := s.getSessionCookie(w, r)
sessionID, err := s.getOrCreateSession(cookie.Value)
if err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
authCtx := auth.GetAuthContext(r)
messagesHTML := s.getMessagesHTML(sessionID)
ports := s.detectOpenPorts()
var previewPort int
if len(ports) > 0 {
previewPort = ports[0]
log.Printf("handleIndex: Detected preview port %d", previewPort)
}
userInitial := ""
if authCtx.IsAuthenticated && authCtx.Session != nil && len(authCtx.Session.Email) > 0 {
userInitial = strings.ToUpper(string(authCtx.Session.Email[0]))
}
data := struct {
Models []models.ModelOption
DefaultModel string
MessagesHTML template.HTML
PreviewPort int
IsAuthenticated bool
UserInitial string
}{
Models: s.getAllModels(),
DefaultModel: "opencode/minimax-m2.5-free",
MessagesHTML: templaserver.Server.handleSend method · go · L64-L156 (93 LOC)internal/server/handlers_chat.go
func (s *Server) handleSend(w http.ResponseWriter, r *http.Request) {
log.Printf("handleSend: received request")
cookie, isNew := s.getSessionCookie(w, r)
if isNew {
log.Printf("handleSend: created new session cookie")
}
sessionID, err := s.getOrCreateSession(cookie.Value)
if err != nil {
log.Printf("handleSend: session error - %v", err)
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
log.Printf("handleSend: using session %s", sessionID)
message := r.FormValue("message")
modelValue := r.FormValue("model")
parts := strings.SplitN(modelValue, "/", 2)
if len(parts) != 2 {
http.Error(w, "Invalid model format", http.StatusBadRequest)
return
}
provider := parts[0]
model := parts[1]
log.Printf("handleSend: message=%q, provider=%q, model=%q", message, provider, model)
if message == "" || provider == "" || model == "" {
log.Printf("handleSend: missing fields")
http.Error(w, "Missing required fields", http.StatusBadRequest)
return
server.Server.handleClear method · go · L381-L410 (30 LOC)internal/server/handlers_chat.go
func (s *Server) handleClear(w http.ResponseWriter, r *http.Request) {
cookie, _ := s.getSessionCookie(w, r)
s.mu.RLock()
sessionID, exists := s.sessions[cookie.Value]
s.mu.RUnlock()
if exists {
req, _ := http.NewRequest("DELETE", fmt.Sprintf("%s/session/%s", s.Sandbox.OpencodeURL(), sessionID), nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("Failed to delete session from opencode: %v", err)
} else {
resp.Body.Close()
}
}
s.mu.Lock()
delete(s.sessions, cookie.Value)
s.mu.Unlock()
_, err := s.getOrCreateSession(cookie.Value)
if err != nil {
http.Error(w, "Failed to create new session", http.StatusInternalServerError)
return
}
s.renderHTML(w, "session-cleared", nil)
}Source: Repobility analyzer · https://repobility.com
server.Server.getMessagesHTML method · go · L412-L469 (58 LOC)internal/server/handlers_chat.go
func (s *Server) getMessagesHTML(sessionID string) string {
resp, err := http.Get(fmt.Sprintf("%s/session/%s/message", s.Sandbox.OpencodeURL(), sessionID))
if err != nil {
log.Printf("getMessagesHTML: Failed to fetch messages: %v", err)
return ""
}
defer resp.Body.Close()
var messages []models.MessageResponse
if err := json.NewDecoder(resp.Body).Decode(&messages); err != nil {
log.Printf("getMessagesHTML: Failed to decode messages: %v", err)
return ""
}
log.Printf("getMessagesHTML: Got %d messages for session %s", len(messages), sessionID)
var html strings.Builder
for _, msg := range messages {
var msgParts []views.MessagePartData
hasContent := false
for _, part := range msg.Parts {
transformedPart := views.TransformMessagePart(s.templates, part)
msgParts = append(msgParts, transformedPart)
if part.Type == "text" && part.Text != "" {
hasContent = true
} else if part.Type != "" {
hasContent = true
}
}
if !hasContent {
continue
server.Server.handleFileContent method · go · L15-L77 (63 LOC)internal/server/handlers_files.go
func (s *Server) handleFileContent(w http.ResponseWriter, r *http.Request) {
filepath := r.URL.Query().Get("path")
if cookie, err := r.Cookie("session"); err == nil && filepath != "" {
s.mu.Lock()
if s.selectedFiles == nil {
s.selectedFiles = make(map[string]string)
}
s.selectedFiles[cookie.Value] = filepath
s.mu.Unlock()
log.Printf("handleFileContent: saved selected file %s for session %s", filepath, cookie.Value)
}
if filepath == "" {
s.renderHTML(w, "code-placeholder", nil)
return
}
if s.Sandbox == nil || !s.Sandbox.IsRunning() {
http.Error(w, "Sandbox not available", http.StatusServiceUnavailable)
return
}
opencodeURL := s.Sandbox.OpencodeURL()
url := fmt.Sprintf("%s/file/content?path=%s", opencodeURL, filepath)
resp, err := http.Get(url)
if err != nil {
log.Printf("Failed to fetch file content: %v", err)
http.Error(w, "Failed to fetch file content", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode server.Server.handleFileList method · go · L79-L108 (30 LOC)internal/server/handlers_files.go
func (s *Server) handleFileList(w http.ResponseWriter, r *http.Request) {
currentPath := r.URL.Query().Get("current")
optionsOnly := r.URL.Query().Get("options_only") == "true"
files, err := s.fetchAllFiles()
if err != nil {
log.Printf("Failed to fetch files from OpenCode: %v", err)
files = []models.FileNode{}
}
lineCount := s.calculateLineCount()
data := struct {
Files []models.FileNode
FileCount int
LineCount int
CurrentPath string
}{
Files: files,
FileCount: len(files),
LineCount: lineCount,
CurrentPath: currentPath,
}
if optionsOnly {
s.renderHTML(w, "file-options-with-counts", data)
} else {
s.renderHTML(w, "file-dropdown", data)
}
}server.Server.handleDownload method · go · L110-L142 (33 LOC)internal/server/handlers_files.go
func (s *Server) handleDownload(w http.ResponseWriter, r *http.Request) {
log.Printf("handleDownload: Starting zip download")
if s.Sandbox == nil {
http.Error(w, "Sandbox not available", http.StatusServiceUnavailable)
return
}
if !s.Sandbox.IsRunning() {
http.Error(w, "Sandbox not running", http.StatusServiceUnavailable)
return
}
zipReader, err := s.Sandbox.DownloadZip()
if err != nil {
log.Printf("handleDownload: Failed to create zip: %v", err)
http.Error(w, "Failed to create zip archive", http.StatusInternalServerError)
return
}
defer zipReader.Close()
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", "attachment; filename=opencode-workspace.zip")
w.Header().Set("Cache-Control", "no-cache")
bytesWritten, err := copyIO(w, zipReader)
if err != nil {
log.Printf("handleDownload: Failed to stream zip: %v", err)
return
}
log.Printf("handleDownload: Successfully streamed %d bytes", bytesWritten)
}server.Server.fetchAllFiles method · go · L145-L188 (44 LOC)internal/server/handlers_files.go
func (s *Server) fetchAllFiles() ([]models.FileNode, error) {
if s.Sandbox == nil || !s.Sandbox.IsRunning() {
return nil, fmt.Errorf("sandbox not available")
}
opencodeURL := s.Sandbox.OpencodeURL()
allFiles := []models.FileNode{}
var fetchDir func(path string) error
fetchDir = func(path string) error {
url := fmt.Sprintf("%s/file?path=%s", opencodeURL, path)
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
var nodes []models.FileNode
if err := json.NewDecoder(resp.Body).Decode(&nodes); err != nil {
return err
}
for _, node := range nodes {
if node.Type == "file" {
allFiles = append(allFiles, node)
} else if node.Type == "directory" {
if err := fetchDir(node.Path); err != nil {
log.Printf("Error fetching directory %s: %v", node.Path, err)
}
}
}
return nil
}
if err := fetchDir("."); err != nil {
return nil, err
}
sort.Slice(allFiles, func(i, j int) bool {
return allFiles[i].Path < server.Server.sendCodeTabUpdates method · go · L191-L226 (36 LOC)internal/server/handlers_files.go
func (s *Server) sendCodeTabUpdates(w http.ResponseWriter, flusher http.Flusher, currentPath string) {
files, err := s.fetchAllFiles()
if err != nil {
log.Printf("Failed to fetch files for code tab update: %v", err)
return
}
lineCount := s.calculateLineCount()
data := struct {
Files []models.FileNode
FileCount int
LineCount int
CurrentPath string
}{
Files: files,
FileCount: len(files),
LineCount: lineCount,
CurrentPath: currentPath,
}
html, err := s.renderHTMLToString("code-updates-oob", data)
if err != nil {
log.Printf("Failed to render code updates OOB: %v", err)
return
}
fmt.Fprintf(w, "event: code-updates\n")
lines := strings.Split(strings.TrimSpace(html), "\n")
for _, line := range lines {
fmt.Fprintf(w, "data: %s\n", line)
}
fmt.Fprintf(w, "\n")
flusher.Flush()
log.Printf("Sent code tab update: %d files, %d lines", data.FileCount, data.LineCount)
}server.Server.handleKillPreviewPort method · go · L229-L258 (30 LOC)internal/server/handlers_files.go
func (s *Server) handleKillPreviewPort(w http.ResponseWriter, r *http.Request) {
port := r.FormValue("port")
if port == "" {
http.Error(w, "Port parameter required", http.StatusBadRequest)
return
}
log.Printf("handleKillPreviewPort: Killing process on port %s", port)
s.mu.RLock()
sessionID := s.workspaceSession
s.mu.RUnlock()
if sessionID == "" {
http.Error(w, "No workspace session available", http.StatusInternalServerError)
return
}
command := fmt.Sprintf("kill $(lsof -t -i:%s) 2>/dev/null || true", port)
_, err := s.executeShellCommand(sessionID, command)
if err != nil {
log.Printf("handleKillPreviewPort: Failed to execute kill command: %v", err)
}
// Small delay to ensure process is killed
// (using time.Sleep is intentional here for subprocess cleanup)
sleepForProcessKill()
s.handleTabPreview(w, r)
}server.Server.detectOpenPorts method · go · L263-L278 (16 LOC)internal/server/handlers_files.go
func (s *Server) detectOpenPorts() []int {
if s.Sandbox == nil || !s.Sandbox.IsRunning() {
return []int{}
}
s.mu.RLock()
sessionID := s.workspaceSession
s.mu.RUnlock()
if sessionID == "" {
log.Printf("detectOpenPorts: no workspace session available")
return []int{}
}
return s.findUserPorts(sessionID)
}Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
server.Server.calculateLineCount method · go · L316-L341 (26 LOC)internal/server/handlers_files.go
func (s *Server) calculateLineCount() int {
if s.Sandbox == nil || !s.Sandbox.IsRunning() {
return 0
}
s.mu.RLock()
sessionID := s.workspaceSession
s.mu.RUnlock()
if sessionID == "" {
log.Printf("calculateLineCount: no workspace session available")
return 0
}
command := "find . -type f -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}'"
output, err := s.executeShellCommand(sessionID, command)
if err != nil {
log.Printf("Failed to run shell command: %v", err)
return 0
}
output = strings.TrimSpace(output)
var lineCount int
fmt.Sscanf(output, "%d", &lineCount)
return lineCount
}server.Server.createProxyDirector method · go · L13-L51 (39 LOC)internal/server/handlers_proxy.go
func (s *Server) createProxyDirector(target *url.URL, pathPrefix string, originalReq *http.Request) func(*http.Request) {
return func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.Host = target.Host
originalPath := originalReq.URL.Path
if pathPrefix != "" && strings.HasPrefix(originalPath, pathPrefix) {
req.URL.Path = strings.TrimPrefix(originalPath, pathPrefix)
if req.URL.Path == "" {
req.URL.Path = "/"
}
} else {
req.URL.Path = originalPath
}
req.URL.RawQuery = originalReq.URL.RawQuery
if originalReq.Header.Get("Upgrade") == "websocket" {
req.Header.Set("Origin", fmt.Sprintf("http://%s", target.Host))
} else if pathPrefix == "/terminal" {
req.Header.Set("Origin", fmt.Sprintf("http://%s", target.Host))
}
if upgrade := originalReq.Header.Get("Upgrade"); upgrade != "" {
req.Header.Set("Upgrade", upgrade)
}
if connection := originalReq.Header.Get("Connection"); connection != "" {
req.Header.server.Server.handleTerminalProxy method · go · L53-L80 (28 LOC)internal/server/handlers_proxy.go
func (s *Server) handleTerminalProxy(w http.ResponseWriter, r *http.Request) {
if s.Sandbox == nil || !s.Sandbox.IsRunning() {
http.Error(w, "Terminal not available", http.StatusServiceUnavailable)
return
}
gottyURL := s.Sandbox.GottyURL()
if gottyURL == "" {
http.Error(w, "Terminal not supported for this sandbox type", http.StatusNotImplemented)
return
}
target, err := url.Parse(gottyURL)
if err != nil {
log.Printf("Error parsing gotty URL: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Director = s.createProxyDirector(target, "/terminal", r)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("Terminal proxy error for %s: %v", r.URL.Path, err)
http.Error(w, fmt.Sprintf("Terminal proxy error: %v", err), http.StatusBadGateway)
}
proxy.ServeHTTP(w, r)
}page 1 / 2next ›