# Buggy code
def update_diagnostics_panel(window: sublime.Window):
    assert window, "missing window!"

    if not window.is_valid():
        debug("ignoring update to closed window")
        return

    base_dir = get_project_path(window)

    diagnostics_by_file = get_window_diagnostics(window)
    if diagnostics_by_file is not None:
        active_panel = window.active_panel()
        is_active_panel = active_panel == "output.diagnostics"

        if diagnostics_by_file:
            panel = ensure_diagnostics_panel(window)
            assert panel, "must have a panel now!"
            panel.settings().set("result_base_dir", base_dir)

            auto_open_panel = False
            to_render = []
            for file_path, source_diagnostics in diagnostics_by_file.items():
                try:
                    relative_file_path = (
                        os.path.relpath(file_path, base_dir) if base_dir else file_path
                    )
                except ValueError:
                    relative_file_path = file_path
                if source_diagnostics:
                    formatted = format_diagnostics(
                        relative_file_path, source_diagnostics
                    )
                    if formatted:
                        to_render.append(formatted)
                        if not auto_open_panel:
                            auto_open_panel = has_relevant_diagnostics(
                                source_diagnostics
                            )

            panel.set_read_only(False)
            panel.run_command("lsp_update_panel", {"characters": "\n".join(to_render)})
            panel.set_read_only(True)

            if settings.auto_show_diagnostics_panel and not active_panel:
                if auto_open_panel:
                    window.run_command("show_panel", {"panel": "output.diagnostics"})

        else:
            panel = window.find_output_panel("diagnostics")
            if panel:
                panel.run_command("lsp_clear_panel")
                if is_active_panel:
                    window.run_command("hide_panel", {"panel": "output.diagnostics"})


# Traceback (BrokenPipeError)
startup, version: 3207 osx x64 channel: stable
executable: /Applications/Sublime Text.app/Contents/MacOS/Sublime Text
working dir: /
packages path: /Users/perm/Library/Application Support/Sublime Text 3/Packages
state path: /Users/perm/Library/Application Support/Sublime Text 3/Local
zip path: /Applications/Sublime Text.app/Contents/MacOS/Packages
zip path: /Users/perm/Library/Application Support/Sublime Text 3/Installed Packages
ignored_packages: ["Vintage"]
pre session restore time: 0.181761
using gpu buffer for window
startup time: 0.258246
environment variables loaded using: /bin/bash -l
reloading plugin Default.arithmetic
reloading plugin Default.auto_indent_tag
reloading plugin Default.block
reloading plugin Default.colors
reloading plugin Default.comment
reloading plugin Default.convert_color_scheme
reloading plugin Default.convert_syntax
reloading plugin Default.copy_path
reloading plugin Default.detect_indentation
reloading plugin Default.echo
reloading plugin Default.exec
reloading plugin Default.fold
reloading plugin Default.font
reloading plugin Default.goto_line
reloading plugin Default.history_list
reloading plugin Default.indentation
reloading plugin Default.install_package_control
reloading plugin Default.kill_ring
reloading plugin Default.mark
reloading plugin Default.new_templates
reloading plugin Default.open_context_url
reloading plugin Default.open_in_browser
reloading plugin Default.pane
reloading plugin Default.paragraph
reloading plugin Default.paste_from_history
reloading plugin Default.profile
reloading plugin Default.quick_panel
reloading plugin Default.rename
reloading plugin Default.run_syntax_tests
reloading plugin Default.save_on_focus_lost
reloading plugin Default.scroll
reloading plugin Default.set_unsaved_view_name
reloading plugin Default.settings
reloading plugin Default.show_scope_name
reloading plugin Default.side_bar
reloading plugin Default.sort
reloading plugin Default.switch_file
reloading plugin Default.symbol
reloading plugin Default.transform
reloading plugin Default.transpose
reloading plugin Default.ui
reloading plugin CSS.css_completions
reloading plugin Diff.diff
reloading plugin HTML.encode_html_entities
reloading plugin HTML.html_completions
reloading plugin ShellScript.ShellScript
reloading plugin 0_package_control_loader.00-package_control
reloading plugin 0_package_control_loader.01-pygments
reloading plugin 0_package_control_loader.50-markupsafe
reloading plugin 0_package_control_loader.50-pymdownx
reloading plugin 0_package_control_loader.50-python-markdown
reloading plugin 0_package_control_loader.50-pyyaml
reloading plugin 0_package_control_loader.51-python-jinja2
reloading plugin 0_package_control_loader.55-mdpopups
reloading plugin LSP.boot
reloading plugin Package Control.1_reloader
reloading plugin Package Control.2_bootstrap
reloading plugin Package Control.Package Control
plugins loaded
LSP: global configs ['jdtls=False', 'phpls=False', 'flow=False', 'reason=False', 'cquery=False', 'clangd=False', 'lsp-tsserver=False', 'eslint=False', 'ocaml=False', 'ruby=False', 'javascript-typescript-langserver=False', 'pyls=False', 'haskell-ide-engine=False', 'ra-lsp=False', 'polymer-ide=False', 'gopls=False', 'vscode-css=False', 'intelephense-ls=False', 'metals=False', 'typescript-language-server=False', 'golsp=False', 'dart=False', 'spider-nc=True', 'rls=False', 'bashls=False']
LSP: Couldn't determine project directory since no folders are open and the current file isn't saved on the disk.
LSP: window 2 starting 1 initial views
LSP: window 2 requests spider-nc for /Users/perm/sicstus/lsptestfolder/foo.pl
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/sicstus/lsptestfolder as a fallback.
LSP: starting in /Users/perm/sicstus/lsptestfolder
LSP: starting ['/usr/bin/nc', 'localhost', '56789']
LSP:  --> initialize
LSP: window 2 added session spider-nc
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/sicstus/lsptestfolder as a fallback.
LSP: project path changed, ending existing sessions
LSP: new path = /Users/perm/sicstus/lsptestfolder
LSP: unloading session spider-nc
LSP:  --> shutdown
Package Control: Skipping automatic upgrade, last run at 2019-08-01 16:21:54, next run at 2019-08-01 17:21:54 or after
LSP:      {'capabilities': {'documentFormattingProvider': True, 'implementationProvider': False, 'codeActionProvider': False, 'callHierarchyProvider': False, 'renameProvider': True, 'typeDefinitionProvider': False, 'workspaceSymbolProvider': True, 'definitionProvider': True, 'documentRangeFormattingProvider': True, 'workspace': {'workspaceFolders': {'supported': True, 'changeNotifications': True}}, 'typeHierarchyProvider': False, 'documentHighlightProvider': True, 'referencesProvider': True, 'textDocumentSync': 2, 'hoverProvider': True, 'documentSymbolProvider': True, 'completionProvider': {'triggerCharacters': ['(']}}}
LSP:  --> initialized
LSP:  --> textDocument/didOpen
LSP:      None
LSP:  --> exit
LSP: session spider-nc ended
LSP: clients for window 2 unloaded
LSP: window 2 requests spider-nc for /Users/perm/sicstus/lsptestfolder/foo.pl
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/sicstus/lsptestfolder as a fallback.
LSP: starting in /Users/perm/sicstus/lsptestfolder
LSP: starting ['/usr/bin/nc', 'localhost', '56789']
LSP:  --> initialize
LSP: window 2 added session spider-nc
LSP: LSP stdout process ended.
using gpu buffer for window
Unable to open /Users/perm/Library/Application Support/Sublime Text 3/Packages/Default/Preferences.sublime-settings
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/Library/Application Support/Sublime Text 3/Packages/User as a fallback.
LSP: window 3 requests spider-nc for /Users/perm/Library/Application Support/Sublime Text 3/Packages/Default/Preferences.sublime-settings
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/Library/Application Support/Sublime Text 3/Packages/User as a fallback.
LSP: starting in /Users/perm/Library/Application Support/Sublime Text 3/Packages/User
LSP: starting ['/usr/bin/nc', 'localhost', '56789']
LSP:  --> initialize
LSP: window 3 added session spider-nc
LSP: LSP stdout process ended.
LSP: no config found or enabled for view /Users/perm/Library/Application Support/Sublime Text 3/Packages/Default/Preferences.sublime-settings
LSP: no config found or enabled for view /Users/perm/Library/Application Support/Sublime Text 3/Packages/Default/Preferences.sublime-settings
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/Library/Application Support/Sublime Text 3/Packages/User as a fallback.
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/Library/Application Support/Sublime Text 3/Packages/User as a fallback.
LSP: Couldn't determine project directory since no folders are open and the current file isn't saved on the disk.
LSP: project path changed, ending existing sessions
LSP: new path = None
LSP: unloading session spider-nc
LSP:  --> shutdown
Failure writing to stdout
Traceback (most recent call last):
File "/Users/perm/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/transports.py", line 227, in write_stdin
self.process.stdin.flush()
BrokenPipeError: [Errno 32] Broken pipe

LSP: Communication to server closed, exiting
LSP: transport failed
LSP: Couldn't determine project directory since no folders are open! Using /Users/perm/sicstus/lsptestfolder as a fallback.
reloading settings Packages/User/Preferences.sublime-settings
reloading settings Packages/User/Preferences.sublime-settings
reloading settings Packages/User/Preferences.sublime-settings
reloading settings Packages/User/Preferences.sublime-settings

# Fixed code
def update_diagnostics_panel(window: sublime.Window):
    assert window, "missing window!"

    if not window.is_valid():
        debug("ignoring update to closed window")
        return

    base_dir = windows.lookup(window).get_project_path()

    diagnostics_by_file = get_window_diagnostics(window)
    if diagnostics_by_file is not None:
        active_panel = window.active_panel()
        is_active_panel = active_panel == "output.diagnostics"

        if diagnostics_by_file:
            panel = ensure_diagnostics_panel(window)
            assert panel, "must have a panel now!"
            panel.settings().set("result_base_dir", base_dir)

            auto_open_panel = False
            to_render = []
            for file_path, source_diagnostics in diagnostics_by_file.items():
                try:
                    relative_file_path = (
                        os.path.relpath(file_path, base_dir) if base_dir else file_path
                    )
                except ValueError:
                    relative_file_path = file_path
                if source_diagnostics:
                    formatted = format_diagnostics(
                        relative_file_path, source_diagnostics
                    )
                    if formatted:
                        to_render.append(formatted)
                        if not auto_open_panel:
                            auto_open_panel = has_relevant_diagnostics(
                                source_diagnostics
                            )

            panel.set_read_only(False)
            panel.run_command("lsp_update_panel", {"characters": "\n".join(to_render)})
            panel.set_read_only(True)

            if settings.auto_show_diagnostics_panel and not active_panel:
                if auto_open_panel:
                    window.run_command("show_panel", {"panel": "output.diagnostics"})

        else:
            panel = window.find_output_panel("diagnostics")
            if panel:
                panel.run_command("lsp_clear_panel")
                if is_active_panel:
                    window.run_command("hide_panel", {"panel": "output.diagnostics"})