- app/: app demo (Kivy/buildozer) da API do robo - software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/) - simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao - modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo - partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd) - projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso - ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender - .gitignore: ignora backups do Blender/FreeCAD e .godot/
699 lines
25 KiB
GDScript
699 lines
25 KiB
GDScript
@tool
|
|
extends Control
|
|
|
|
var editor_interface: EditorInterface
|
|
var agent: ClaudeGodotAgent
|
|
|
|
var _log_scroll: ScrollContainer
|
|
var _log_container: VBoxContainer
|
|
var _input: LineEdit
|
|
var _send_button: Button
|
|
var _stop_button: Button
|
|
var _attach_button: Button
|
|
var _activity: Label
|
|
var _activity_timer: Timer
|
|
var _turn_started_ms := 0
|
|
var _spinner_frame := 0
|
|
var _streamed_characters := 0
|
|
var _token_label: Label
|
|
var _provider_option: OptionButton
|
|
var _model_picker: ClaudeGodotModelPicker
|
|
var _api_key_field: LineEdit
|
|
var _mcp_server: ClaudeGodotMcpServer
|
|
var _mcp_button: Button
|
|
var _cost_label: Label
|
|
var _file_dialog: EditorFileDialog
|
|
var _session_option: OptionButton
|
|
var _delete_dialog: ConfirmationDialog
|
|
var _attachments_row: HBoxContainer
|
|
var _input_estimate_label: Label
|
|
var _count_timer: Timer
|
|
var _count_generation := 0
|
|
var _task_strip: ClaudeGodotTaskStrip
|
|
|
|
## Remembers the key/model typed per-provider so switching providers doesn't lose them.
|
|
var _provider_state: Dictionary = {}
|
|
## Images picked but not sent yet: [{bytes: PackedByteArray, mime: String, path: String}].
|
|
var _pending_images: Array = []
|
|
## The card awaiting its result; see _on_tool_call.
|
|
var _pending_tool_card: ClaudeGodotToolCard = null
|
|
## Queue id -> the row showing it, so the same row can become the sent
|
|
## message instead of the queued one appearing twice.
|
|
var _queued_rows: Dictionary = {}
|
|
|
|
func _ready() -> void:
|
|
custom_minimum_size = Vector2(340, 0)
|
|
_build_ui()
|
|
|
|
agent = ClaudeGodotAgent.new()
|
|
add_child(agent)
|
|
agent.assistant_text.connect(_on_assistant_text)
|
|
agent.assistant_reasoning.connect(_on_assistant_reasoning)
|
|
agent.step_limit_reached.connect(_on_step_limit_reached)
|
|
agent.context_compacted.connect(_on_context_compacted)
|
|
agent.tool_call.connect(_on_tool_call)
|
|
agent.tool_result.connect(_on_tool_result)
|
|
agent.agent_error.connect(_on_agent_error)
|
|
agent.usage_updated.connect(_on_usage_updated)
|
|
agent.stream_progress.connect(func(characters):
|
|
_streamed_characters = characters
|
|
_refresh_activity())
|
|
|
|
# Drives the spinner and the elapsed seconds; only runs during a turn.
|
|
_activity_timer = Timer.new()
|
|
_activity_timer.wait_time = 0.1
|
|
_activity_timer.timeout.connect(_refresh_activity)
|
|
add_child(_activity_timer)
|
|
agent.session_changed.connect(_on_session_changed)
|
|
agent.message_queued.connect(_on_message_queued)
|
|
agent.message_dequeued.connect(_on_message_dequeued)
|
|
agent.message_cancelled.connect(_on_message_cancelled)
|
|
agent.session_described.connect(func(_title): _refresh_sessions())
|
|
agent.background_task_changed.connect(func(_run): _task_strip.refresh())
|
|
agent.background_task_finished.connect(_on_background_task_finished)
|
|
agent.turn_started.connect(func(): _set_busy(true))
|
|
agent.turn_finished.connect(func():
|
|
_set_busy(false)
|
|
_refresh_sessions())
|
|
|
|
_mcp_server = ClaudeGodotMcpServer.new()
|
|
add_child(_mcp_server)
|
|
_mcp_server.client_tool_call.connect(_on_mcp_tool_call)
|
|
_mcp_server.client_tool_result.connect(_on_tool_result)
|
|
|
|
_file_dialog = EditorFileDialog.new()
|
|
_file_dialog.file_mode = EditorFileDialog.FILE_MODE_OPEN_FILE
|
|
_file_dialog.access = EditorFileDialog.ACCESS_FILESYSTEM
|
|
_file_dialog.add_filter("*.png, *.jpg, *.jpeg, *.webp", "Images")
|
|
_file_dialog.file_selected.connect(_on_image_selected)
|
|
add_child(_file_dialog)
|
|
|
|
# Counting is a request, so it waits for a pause in typing rather than
|
|
# firing per keystroke.
|
|
_count_timer = Timer.new()
|
|
_count_timer.wait_time = 0.7
|
|
_count_timer.one_shot = true
|
|
_count_timer.timeout.connect(_count_exact_tokens)
|
|
add_child(_count_timer)
|
|
|
|
_delete_dialog = ConfirmationDialog.new()
|
|
_delete_dialog.title = "Delete session"
|
|
_delete_dialog.confirmed.connect(_on_delete_confirmed)
|
|
add_child(_delete_dialog)
|
|
|
|
_populate_providers()
|
|
_refresh_sessions()
|
|
_load_preferences()
|
|
var start_index := _index_for_preset(ClaudeGodotPreferences.get_value("preferred_provider", "anthropic"))
|
|
_provider_option.selected = start_index
|
|
_on_provider_selected(start_index)
|
|
|
|
func _build_ui() -> void:
|
|
var vbox := VBoxContainer.new()
|
|
vbox.set_anchors_preset(Control.PRESET_FULL_RECT)
|
|
add_child(vbox)
|
|
|
|
var session_row := HBoxContainer.new()
|
|
vbox.add_child(session_row)
|
|
|
|
_session_option = OptionButton.new()
|
|
_session_option.tooltip_text = "Start a new chat, or reopen a saved one. Sessions live in user://.claude-godot/sessions/ as .chat files."
|
|
_session_option.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
_session_option.item_selected.connect(_on_session_selected)
|
|
session_row.add_child(_session_option)
|
|
|
|
var delete_button := Button.new()
|
|
delete_button.text = "🗑"
|
|
delete_button.tooltip_text = "Delete the session shown here"
|
|
delete_button.pressed.connect(_on_delete_pressed)
|
|
session_row.add_child(delete_button)
|
|
|
|
_provider_option = OptionButton.new()
|
|
_provider_option.item_selected.connect(_on_provider_selected)
|
|
vbox.add_child(_provider_option)
|
|
|
|
_model_picker = ClaudeGodotModelPicker.new()
|
|
_model_picker.model_changed.connect(_on_model_changed)
|
|
vbox.add_child(_model_picker)
|
|
|
|
_api_key_field = LineEdit.new()
|
|
_api_key_field.secret = true
|
|
_api_key_field.text_changed.connect(_on_api_key_changed)
|
|
vbox.add_child(_api_key_field)
|
|
|
|
var key_note := Label.new()
|
|
key_note.text = "Saved locally in plain text (user://claude_godot/preferences.csv), not in your project or git."
|
|
key_note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
|
key_note.add_theme_font_size_override("font_size", 10)
|
|
vbox.add_child(key_note)
|
|
|
|
_cost_label = Label.new()
|
|
_cost_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
|
_cost_label.add_theme_font_size_override("font_size", 10)
|
|
vbox.add_child(_cost_label)
|
|
|
|
vbox.add_child(HSeparator.new())
|
|
|
|
_mcp_button = Button.new()
|
|
_mcp_button.text = "Connect to Claude Code (MCP)"
|
|
_mcp_button.tooltip_text = "Runs a local MCP server so Claude Code (or any MCP client) can read/list/write files in this project directly, without going through an LLM API key here."
|
|
_mcp_button.pressed.connect(_on_mcp_button_pressed)
|
|
vbox.add_child(_mcp_button)
|
|
|
|
vbox.add_child(HSeparator.new())
|
|
|
|
_log_scroll = ScrollContainer.new()
|
|
_log_scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL
|
|
_log_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
|
|
vbox.add_child(_log_scroll)
|
|
|
|
_log_container = VBoxContainer.new()
|
|
_log_container.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
_log_scroll.add_child(_log_container)
|
|
|
|
_activity = Label.new()
|
|
_activity.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
|
_activity.add_theme_font_size_override("font_size", 11)
|
|
_activity.visible = false
|
|
vbox.add_child(_activity)
|
|
|
|
# Above the input, below the transcript: the one place a run working the
|
|
# project without a visible conversation shows up.
|
|
_task_strip = ClaudeGodotTaskStrip.new()
|
|
_task_strip.visible = false
|
|
vbox.add_child(_task_strip)
|
|
|
|
_attachments_row = HBoxContainer.new()
|
|
vbox.add_child(_attachments_row)
|
|
|
|
_input_estimate_label = Label.new()
|
|
_input_estimate_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
|
_input_estimate_label.add_theme_font_size_override("font_size", 10)
|
|
vbox.add_child(_input_estimate_label)
|
|
|
|
var input_row := HBoxContainer.new()
|
|
vbox.add_child(input_row)
|
|
|
|
_attach_button = Button.new()
|
|
_attach_button.text = "📎"
|
|
_attach_button.tooltip_text = "Attach an image"
|
|
_attach_button.pressed.connect(_on_attach_pressed)
|
|
input_row.add_child(_attach_button)
|
|
|
|
_input = LineEdit.new()
|
|
_input.placeholder_text = "Ask Claude to build something..."
|
|
_input.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
_input.text_submitted.connect(func(_t): _on_send())
|
|
_input.text_changed.connect(func(_t): _update_input_estimate())
|
|
input_row.add_child(_input)
|
|
|
|
_send_button = Button.new()
|
|
_send_button.text = "Send"
|
|
_send_button.pressed.connect(_on_send)
|
|
input_row.add_child(_send_button)
|
|
|
|
_stop_button = Button.new()
|
|
_stop_button.text = "Stop"
|
|
_stop_button.disabled = true
|
|
_stop_button.pressed.connect(_on_stop_pressed)
|
|
input_row.add_child(_stop_button)
|
|
|
|
_token_label = Label.new()
|
|
_token_label.text = "Tokens: 0 in / 0 out"
|
|
_token_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
|
_token_label.add_theme_font_size_override("font_size", 10)
|
|
vbox.add_child(_token_label)
|
|
|
|
func _populate_providers() -> void:
|
|
for preset in ClaudeGodotProviderPresets.get_presets():
|
|
_provider_option.add_item(preset["label"])
|
|
|
|
## Pulls saved provider/model/api-key choices from user:// into _provider_state.
|
|
func _load_preferences() -> void:
|
|
for preset in ClaudeGodotProviderPresets.get_presets():
|
|
var pid: String = preset["id"]
|
|
_provider_state[pid] = {
|
|
"model": ClaudeGodotPreferences.get_value("model:" + pid, preset["default_model"]),
|
|
"api_key": ClaudeGodotPreferences.get_value("api_key:" + pid, ""),
|
|
}
|
|
|
|
func _index_for_preset(preset_id: String) -> int:
|
|
var presets := ClaudeGodotProviderPresets.get_presets()
|
|
for i in range(presets.size()):
|
|
if presets[i]["id"] == preset_id:
|
|
return i
|
|
return 0
|
|
|
|
func _current_preset_id() -> String:
|
|
return ClaudeGodotProviderPresets.get_presets()[_provider_option.selected]["id"]
|
|
|
|
func _on_provider_selected(_index: int) -> void:
|
|
var preset_id := _current_preset_id()
|
|
var state: Dictionary = _provider_state[preset_id]
|
|
agent.set_preset(preset_id, state["model"], state["api_key"])
|
|
_model_picker.set_models(agent.preset.get("known_models", []), state["model"])
|
|
_api_key_field.text = state["api_key"]
|
|
_api_key_field.placeholder_text = "API key (or set %s)" % agent.preset["env_var"]
|
|
_update_cost_label()
|
|
ClaudeGodotPreferences.set_value("preferred_provider", preset_id)
|
|
|
|
func _on_model_changed(text: String) -> void:
|
|
var pid := _current_preset_id()
|
|
_provider_state[pid]["model"] = text
|
|
agent.provider.model = text
|
|
_update_cost_label()
|
|
ClaudeGodotPreferences.set_value("model:" + pid, text)
|
|
|
|
func _on_api_key_changed(text: String) -> void:
|
|
var pid := _current_preset_id()
|
|
_provider_state[pid]["api_key"] = text
|
|
agent.provider.api_key = text
|
|
ClaudeGodotPreferences.set_value("api_key:" + pid, text)
|
|
|
|
func _update_cost_label() -> void:
|
|
var costs: Dictionary = agent.preset.get("model_costs", {})
|
|
var model := _model_picker.get_model()
|
|
if not costs.has(model):
|
|
_cost_label.text = "Cost: unknown (verify current pricing with the provider)"
|
|
return
|
|
var c: Dictionary = costs[model]
|
|
var parts: Array = []
|
|
if c.has("input"):
|
|
parts.append("in $%.2f" % c["input"])
|
|
if c.has("output"):
|
|
parts.append("out $%.2f" % c["output"])
|
|
_cost_label.text = "Cost: %s per MTok" % " / ".join(parts)
|
|
|
|
func _on_usage_updated(total_input: int, total_output: int) -> void:
|
|
var line := "Tokens: %s in / %s out" % [_format_count(total_input), _format_count(total_output)]
|
|
if agent.total_cached_tokens > 0:
|
|
line += " (%s cached)" % _format_count(agent.total_cached_tokens)
|
|
if agent.total_reasoning_tokens > 0:
|
|
line += " · %s reasoning" % _format_count(agent.total_reasoning_tokens)
|
|
# What the provider says it charged, when it says — better than the
|
|
# per-MTok rate in providers.csv, which is a figure someone typed in.
|
|
if agent.total_cost > 0.0:
|
|
line += " · $%.4f spent" % agent.total_cost
|
|
_token_label.text = line
|
|
|
|
static func _format_count(n: int) -> String:
|
|
if n >= 1_000_000:
|
|
return "%.1fM" % (n / 1_000_000.0)
|
|
if n >= 1_000:
|
|
return "%.1fk" % (n / 1_000.0)
|
|
return str(n)
|
|
|
|
func _on_mcp_button_pressed() -> void:
|
|
if _mcp_server.is_running():
|
|
_mcp_server.stop()
|
|
_mcp_button.text = "Connect to Claude Code (MCP)"
|
|
_append_turn("[color=gray]MCP server stopped.[/color]", "MCP server stopped.")
|
|
return
|
|
|
|
var result := _mcp_server.start(8787)
|
|
if result.has("error"):
|
|
var err_text: String = str(result["error"])
|
|
_append_turn("[color=red]MCP error: %s[/color]" % err_text.replace("[", "[lb]"), err_text)
|
|
return
|
|
|
|
var cmd := "claude mcp add --transport http claude-godot http://127.0.0.1:%d/mcp" % _mcp_server.port
|
|
DisplayServer.clipboard_set(cmd)
|
|
_mcp_button.text = "Disconnect (MCP running on :%d)" % _mcp_server.port
|
|
_append_turn(
|
|
"[b]MCP server listening on 127.0.0.1:%d.[/b] Command copied to clipboard — run it in your Claude Code terminal:\n[code]%s[/code]" % [_mcp_server.port, cmd],
|
|
cmd
|
|
)
|
|
|
|
func _on_mcp_tool_call(tool_name: String, input: Dictionary) -> void:
|
|
_on_tool_call("[MCP] " + tool_name, input)
|
|
|
|
## Item 0 starts a new chat; the rest reopen a saved session.
|
|
func _refresh_sessions() -> void:
|
|
_session_option.clear()
|
|
_session_option.add_item("+ New chat")
|
|
_session_option.set_item_metadata(0, "")
|
|
for s in ClaudeGodotSessionStore.list_sessions():
|
|
# Named sessions read as their title; unnamed ones fall back to the
|
|
# opening question, marked so the difference is visible.
|
|
var label: String = s["title"] if s["titled"] else "· %s" % s["title"]
|
|
_session_option.add_item(label)
|
|
_session_option.set_item_metadata(_session_option.item_count - 1, s["id"])
|
|
if s["id"] == agent.session_id:
|
|
_session_option.selected = _session_option.item_count - 1
|
|
|
|
func _on_session_selected(index: int) -> void:
|
|
var target: String = str(_session_option.get_item_metadata(index))
|
|
if target == "":
|
|
agent.new_session()
|
|
return
|
|
if target == agent.session_id:
|
|
return
|
|
var result := agent.resume_session(target)
|
|
if result.has("error"):
|
|
_append_turn("[color=red]%s[/color]" % str(result["error"]).replace("[", "[lb]"), str(result["error"]))
|
|
|
|
## Deleting is irreversible and the file is outside the project, so it asks
|
|
## first and names what it is about to remove.
|
|
func _on_delete_pressed() -> void:
|
|
var target := str(_session_option.get_item_metadata(_session_option.selected))
|
|
if target == "":
|
|
return
|
|
_delete_dialog.dialog_text = "Delete \"%s\"?\n\nThis removes %s from disk and cannot be undone." % [
|
|
_session_option.get_item_text(_session_option.selected),
|
|
ClaudeGodotSessionStore.path_for(target),
|
|
]
|
|
_delete_dialog.popup_centered()
|
|
|
|
func _on_delete_confirmed() -> void:
|
|
var target := str(_session_option.get_item_metadata(_session_option.selected))
|
|
if target == "":
|
|
return
|
|
|
|
var was_current := target == agent.session_id
|
|
var result := ClaudeGodotSessionStore.delete(target)
|
|
if result.has("error"):
|
|
_append_turn("[color=red]%s[/color]" % str(result["error"]).replace("[", "[lb]"), str(result["error"]))
|
|
return
|
|
|
|
# Deleting the session you are in would otherwise leave the dock holding a
|
|
# conversation whose file is gone, and saving would just recreate it.
|
|
if was_current:
|
|
agent.new_session()
|
|
else:
|
|
_refresh_sessions()
|
|
|
|
## A background run ended. It has no transcript of its own in the dock, so its
|
|
## outcome is announced in this one — otherwise a task that failed while the
|
|
## user was reading something else leaves no trace until they think to look.
|
|
func _on_background_task_finished(run: ClaudeGodotTaskRun) -> void:
|
|
_task_strip.refresh()
|
|
var headline := "Background task %s (%s) %s after %d step%s." % [
|
|
run.id, run.label, run.state_name(), run.steps, "" if run.steps == 1 else "s",
|
|
]
|
|
var color := "green" if run.state == ClaudeGodotTaskRun.State.DONE else "red"
|
|
var body := headline if run.summary == "" else "%s\n%s" % [headline, run.summary]
|
|
_append_turn(
|
|
"[color=%s]%s[/color]\n%s" % [color, headline.replace("[", "[lb]"), ClaudeGodotMarkdown.to_bbcode(run.summary)],
|
|
body,
|
|
)
|
|
|
|
func _on_session_changed(_session_id: String) -> void:
|
|
_rebuild_transcript()
|
|
_refresh_sessions()
|
|
|
|
## Redraws the log from the restored history. The wire shapes differ per
|
|
## protocol, so this reads what it recognises and summarises the rest rather
|
|
## than pretending to reproduce the original rendering exactly.
|
|
func _rebuild_transcript() -> void:
|
|
for child in _log_container.get_children():
|
|
child.queue_free()
|
|
_pending_tool_card = null
|
|
|
|
for message in agent.provider.get_history():
|
|
if not (message is Dictionary):
|
|
continue
|
|
var role: String = message.get("role", "")
|
|
var text := _text_of(message)
|
|
if text == "":
|
|
continue
|
|
if role == "user":
|
|
_append_turn("[b]You:[/b] %s" % text.replace("[", "[lb]"), text)
|
|
elif role == "assistant":
|
|
_append_turn("[b]Claude:[/b] %s" % ClaudeGodotMarkdown.to_bbcode(text), text)
|
|
|
|
## Pulls readable text out of a message in any of the three wire shapes.
|
|
func _text_of(message: Dictionary) -> String:
|
|
var content = message.get("content", null)
|
|
if content is String:
|
|
return content
|
|
if not (content is Array):
|
|
return ""
|
|
|
|
var parts: Array = []
|
|
for part in content:
|
|
if not (part is Dictionary):
|
|
continue
|
|
match part.get("type", ""):
|
|
"text", "input_text", "output_text":
|
|
parts.append(str(part.get("text", "")))
|
|
"image", "input_image", "image_url":
|
|
parts.append("[image]")
|
|
return "\n".join(parts)
|
|
|
|
func _on_attach_pressed() -> void:
|
|
_file_dialog.popup_centered_ratio(0.7)
|
|
|
|
func _on_image_selected(path: String) -> void:
|
|
var f := FileAccess.open(path, FileAccess.READ)
|
|
if f == null:
|
|
var msg := "Could not read image: %s" % path
|
|
_append_turn("[color=red]%s[/color]" % msg.replace("[", "[lb]"), msg)
|
|
return
|
|
var bytes := f.get_buffer(f.get_length())
|
|
f.close()
|
|
_pending_images.append({"bytes": bytes, "mime": _mime_for_extension(path.get_extension().to_lower()), "path": path})
|
|
_refresh_attachments_ui()
|
|
_update_input_estimate()
|
|
|
|
static func _mime_for_extension(ext: String) -> String:
|
|
match ext:
|
|
"jpg", "jpeg":
|
|
return "image/jpeg"
|
|
"webp":
|
|
return "image/webp"
|
|
_:
|
|
return "image/png"
|
|
|
|
func _refresh_attachments_ui() -> void:
|
|
for child in _attachments_row.get_children():
|
|
child.queue_free()
|
|
for i in range(_pending_images.size()):
|
|
var img: Dictionary = _pending_images[i]
|
|
var chip := HBoxContainer.new()
|
|
|
|
var lbl := Label.new()
|
|
lbl.text = "🖼 " + (img["path"] as String).get_file()
|
|
lbl.add_theme_font_size_override("font_size", 10)
|
|
chip.add_child(lbl)
|
|
|
|
var remove_btn := Button.new()
|
|
remove_btn.text = "x"
|
|
remove_btn.pressed.connect(_on_remove_attachment.bind(i))
|
|
chip.add_child(remove_btn)
|
|
|
|
_attachments_row.add_child(chip)
|
|
|
|
func _on_remove_attachment(index: int) -> void:
|
|
_pending_images.remove_at(index)
|
|
_refresh_attachments_ui()
|
|
_update_input_estimate()
|
|
|
|
## Rough, provider-agnostic estimate (~4 chars/token for text, a flat
|
|
## ~1500 tokens/image) of what the *next* message will cost — not real
|
|
## usage. Anthropic has an actual free count_tokens endpoint, but none of
|
|
## the OpenAI-compatible providers do, so this stays a local heuristic for
|
|
## everyone rather than being accurate for one provider and silent for six.
|
|
func _update_input_estimate() -> void:
|
|
var chars := _input.text.length()
|
|
var text_tokens := int(ceil(chars / 4.0))
|
|
var image_tokens := _pending_images.size() * 1500
|
|
var total := text_tokens + image_tokens
|
|
|
|
# Any edit invalidates a count already in flight.
|
|
_count_generation += 1
|
|
if total == 0:
|
|
_input_estimate_label.text = ""
|
|
_count_timer.stop()
|
|
return
|
|
|
|
_input_estimate_label.text = "~%s tokens (estimate)" % _format_count(total)
|
|
_count_timer.start()
|
|
|
|
## Replaces the estimate with the provider's own number, for the two that
|
|
## offer one — Anthropic's count_tokens and OpenAI's input_tokens. Everyone
|
|
## else 404s on it, so the estimate stands.
|
|
func _count_exact_tokens() -> void:
|
|
var generation := _count_generation
|
|
var draft := _input.text
|
|
var exact: int = await agent.count_input_tokens(draft)
|
|
|
|
# Typing moved on, or this provider has no endpoint.
|
|
if exact < 0 or generation != _count_generation:
|
|
return
|
|
_input_estimate_label.text = "%s tokens in context" % _format_count(exact)
|
|
|
|
func _on_stop_pressed() -> void:
|
|
agent.cancel()
|
|
|
|
func _on_send() -> void:
|
|
var text := _input.text.strip_edges()
|
|
if text == "" and _pending_images.is_empty():
|
|
return
|
|
|
|
# When a turn is running this message will be queued, and the queued
|
|
# signal draws its own row — so only draw one here when it goes out now.
|
|
if not agent.is_turn_running():
|
|
var line := "[b]You:[/b] %s" % text.replace("[", "[lb]")
|
|
if not _pending_images.is_empty():
|
|
line += " [color=gray](%d image%s attached)[/color]" % [_pending_images.size(), "s" if _pending_images.size() != 1 else ""]
|
|
_append_turn(line, text)
|
|
|
|
_input.text = ""
|
|
var images := _pending_images.duplicate()
|
|
_pending_images.clear()
|
|
_refresh_attachments_ui()
|
|
agent.send_user_message(text, images)
|
|
|
|
## A queued message gets its row straight away, marked as waiting, with an
|
|
## ✕ that pulls it back into the input box.
|
|
func _on_message_queued(id: int, text: String) -> void:
|
|
var row := HBoxContainer.new()
|
|
row.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
|
|
var label := RichTextLabel.new()
|
|
label.bbcode_enabled = true
|
|
label.fit_content = true
|
|
label.scroll_active = false
|
|
label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
label.append_text(_queued_bbcode(text))
|
|
row.add_child(label)
|
|
|
|
var cancel_button := Button.new()
|
|
cancel_button.text = "✕"
|
|
cancel_button.tooltip_text = "Take this back out of the queue"
|
|
cancel_button.pressed.connect(func(): _on_cancel_queued(id))
|
|
row.add_child(cancel_button)
|
|
|
|
_queued_rows[id] = {"row": row, "label": label, "cancel": cancel_button}
|
|
_log_container.add_child(row)
|
|
_scroll_to_bottom()
|
|
|
|
func _queued_bbcode(text: String) -> String:
|
|
return "[color=#e8a33d]⏳ queued[/color] %s" % text.replace("[", "[lb]")
|
|
|
|
## The same row becomes the sent message, so nothing appears twice.
|
|
func _on_message_dequeued(id: int, text: String) -> void:
|
|
if not _queued_rows.has(id):
|
|
return
|
|
var entry: Dictionary = _queued_rows[id]
|
|
var label: RichTextLabel = entry["label"]
|
|
label.clear()
|
|
label.append_text("[b]You:[/b] %s" % text.replace("[", "[lb]"))
|
|
(entry["cancel"] as Button).queue_free()
|
|
_queued_rows.erase(id)
|
|
|
|
func _on_message_cancelled(id: int) -> void:
|
|
if not _queued_rows.has(id):
|
|
return
|
|
(_queued_rows[id]["row"] as Control).queue_free()
|
|
_queued_rows.erase(id)
|
|
|
|
func _on_cancel_queued(id: int) -> void:
|
|
var text := agent.cancel_queued(id)
|
|
if text != "":
|
|
_input.text = text
|
|
_update_input_estimate()
|
|
|
|
func _on_assistant_text(text: String) -> void:
|
|
_append_turn("[b]Claude:[/b] %s" % ClaudeGodotMarkdown.to_bbcode(text), text)
|
|
|
|
func _on_assistant_reasoning(text: String) -> void:
|
|
var card := ClaudeGodotReasoningCard.new()
|
|
_append_row(card, func(): return card.to_plain_text())
|
|
card.setup(text)
|
|
|
|
func _on_step_limit_reached(steps: int) -> void:
|
|
var msg := "Reached the %d-step limit for one message — asking for a wrap-up instead of running more tools. Raise max_steps_per_turn in user://claude_godot/preferences.csv to allow more." % steps
|
|
_append_turn("[color=#e8a33d]%s[/color]" % msg, msg)
|
|
|
|
func _on_context_compacted(before_tokens: int, after_tokens: int, source: String) -> void:
|
|
var what := "auto"
|
|
if source == "manual":
|
|
what = "on request"
|
|
elif source == "overflow":
|
|
what = "to fit the context limit"
|
|
var msg := "Context compacted (%s): ~%s → ~%s tokens." % [what, _format_count(before_tokens), _format_count(after_tokens)]
|
|
_append_turn("[color=#8a8a8a]%s[/color]" % msg, msg)
|
|
|
|
## Tool calls get a card each, created when the call starts and completed
|
|
## when its result arrives — the two always arrive in that order, one pair
|
|
## at a time, from both the local agent and the MCP server.
|
|
func _on_tool_call(tool_name: String, input: Dictionary) -> void:
|
|
var card := ClaudeGodotToolCard.new()
|
|
_pending_tool_card = card
|
|
_append_row(card, func(): return card.to_plain_text())
|
|
card.setup(tool_name, input)
|
|
|
|
func _on_tool_result(_tool_name: String, result: Dictionary) -> void:
|
|
if _pending_tool_card == null:
|
|
return
|
|
_pending_tool_card.set_result(result, agent.supports_vision())
|
|
_pending_tool_card = null
|
|
|
|
func _on_agent_error(message: String) -> void:
|
|
if message == "Cancelled.":
|
|
_append_turn("[color=gray]— stopped —[/color]", "— stopped —")
|
|
return
|
|
_append_turn("[color=red]Error: %s[/color]" % message.replace("[", "[lb]"), message)
|
|
|
|
## Adds one turn panel to the log: its own RichTextLabel (so each turn sizes
|
|
## to its own content instead of one endless growing label) plus a small
|
|
## clipboard button that copies plain_text — not the BBCode source.
|
|
func _append_turn(bbcode: String, plain_text: String) -> void:
|
|
var rtl := RichTextLabel.new()
|
|
rtl.bbcode_enabled = true
|
|
rtl.fit_content = true
|
|
rtl.scroll_active = false
|
|
rtl.append_text(bbcode)
|
|
_append_row(rtl, func(): return plain_text)
|
|
|
|
## Adds one row to the log: the content plus its clipboard button. The text is
|
|
## fetched through a callable because a tool card's content keeps changing
|
|
## after its row has been added.
|
|
func _append_row(content: Control, plain_text_provider: Callable) -> void:
|
|
var row := HBoxContainer.new()
|
|
row.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
content.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
|
row.add_child(content)
|
|
|
|
var copy_btn := Button.new()
|
|
copy_btn.text = "📋"
|
|
copy_btn.tooltip_text = "Copy this message"
|
|
copy_btn.pressed.connect(func(): DisplayServer.clipboard_set(plain_text_provider.call()))
|
|
row.add_child(copy_btn)
|
|
|
|
_log_container.add_child(row)
|
|
_scroll_to_bottom()
|
|
|
|
func _scroll_to_bottom() -> void:
|
|
await get_tree().process_frame
|
|
_log_scroll.scroll_vertical = int(_log_scroll.get_v_scroll_bar().max_value)
|
|
|
|
const SPINNER_FRAMES := ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
|
|
|
|
func _set_busy(busy: bool) -> void:
|
|
# Left enabled during a turn: sending now queues rather than corrupting
|
|
# the turn in flight, and queueing is the point.
|
|
_send_button.disabled = false
|
|
_stop_button.disabled = not busy
|
|
_activity.visible = busy
|
|
if busy:
|
|
_turn_started_ms = Time.get_ticks_msec()
|
|
_streamed_characters = 0
|
|
_spinner_frame = 0
|
|
_refresh_activity()
|
|
_activity_timer.start()
|
|
else:
|
|
_activity_timer.stop()
|
|
|
|
## "⠹ Thinking 4s · ~120 tokens". The token figure is derived from streamed
|
|
## characters, since the real count only lands with the final usage — the
|
|
## tilde is there to say so.
|
|
func _refresh_activity() -> void:
|
|
_spinner_frame = (_spinner_frame + 1) % SPINNER_FRAMES.size()
|
|
var seconds := (Time.get_ticks_msec() - _turn_started_ms) / 1000
|
|
var line := "%s Thinking %ds" % [SPINNER_FRAMES[_spinner_frame], seconds]
|
|
if _streamed_characters > 0:
|
|
line += " · ~%s tokens" % _format_count(int(ceil(_streamed_characters / 4.0)))
|
|
_activity.text = line
|